text:
Print N Squared
Write a program or function that takes in a non-negative integer N from stdin or as a function argument. It must print or return a string of a hollow ASCII-art square whose sides are each made with N copies of the number N.
Specifically:
If N is 0, no copies of N are used, so there should be no output (or only a single trailing newline).
If N is 1, the output is:
1

If N is 2:
22
22

If N is 3:
333
3 3
333

If N is 4:
4444
4  4
4  4
4444

If N is 5:
55555
5   5
5   5
5   5
55555

The pattern continues for 6 through 9.
If N is 10, the output is:
10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010

Notice that this is not actually square. It is 10 rows tall but 20 columns wide because 10 is two characters long. This is intended. The point is that each side of the "square" contains N copies of N. So all inputs beyond 9 will technically be ASCII rectangles.
For example, if N is 23, the output is:
2323232323232323232323232323232323232323232323
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
2323232323232323232323232323232323232323232323
Here are Pastebins of the required outputs for 99, 100, 111, and 123 (they may look wrong in a browser but in a text editor they'll look correct). The output for 1000 is to large for Pastebin but it would have 1000 rows and 4000 columns. Numbers with 4 or more digits must work just like smaller numbers.
Details:

N must be written in the usual decimal number representation, with no + sign or other non-digits.
The hollow area must only be filled with spaces.
No lines should have leading or trailing spaces.
A single newline after the squares' last line is optionally allowed.
Languages written after this challenge was made are welcome, they just aren't eligible to win.
The shortest code in bytes wins!

The square for n=10 looks more square than for n=5. Hooray, non-square fonts!

May we take the integer as a string?

@Nᴮᶻ Yes you may

Jolf, 31 27 25 23 bytes
?=1i1ρρ,aii+*3έέi*li

This is encoded in the ISO-8859-7 encoding and contains unprintables, so here's a hexdump:
0000000: 3f3d 3169 31f1 f12c 6169 692b 2a33 dd05  ?=1i1..,aii+*3..
0000010: dd69 052a 056c 69                        .i.*.li

Try this fiddle online or verify all test cases at once (use the full run button).
This exits with an error for n = 0, which is allowed by default.
Massive thanks to Conor for golfing off 4 6! bytes. inb4 crossed out four still looks like a four comment
Explanation
?=1i1ρρ,aii+*3έ\x05έi\x05*\x05li

?=1i1                             if input is 1 return 1, otherwise...
       ,aii+*3έ\x05               draw an input x input hollow box of tabs
      ρ            έi             replace all tabs with input
     ρ               \x05*\x05li  replace all spaces with spaces * length of input

How did you generate the hexdump?

@CᴏɴᴏʀO'Bʀɪᴇɴ I used xxd. You can reverse it with xxd -r.

Shtriped, 317 bytes
While I'm making the question, I may as show off my new "purist" language.
@ f x
 d x
 f
 @ f x
+ x y
 +
  i x
 @ + y
 h x
} x y
 e 1
 i 1
 d y
 d 1
 d x
 } x y
e 0
e 2
i 2
i 2
e 6
+ 2 2 6
+ 2 6 6
e T
+ 2 2 T
+ 6 T T
e N
t N
e P
+ T 0 P
e L
i L
*
 e x
 *
  + P x x
 @ * T
 h x
~
 } N P 0
 d 0
 i L
 * P
 ~
~
#
 p N
-
 s 6
_
 @ - L
$
 #
 @ _ n
 #
 s 2
@ # N
e n
+ N 0 n
d n
d n
s 2
@ $ n
@ # N
(definitely works in v1.0.0)
There are no math operations built into Shtriped except increment and decrement. There's also no looping or conditionals, so all of these thing need to be built up from scratch in every program.
That's what my program does, e.g. @ is essentially a for loop, + is an addition function, } is >=. The actual output is only produced in the last 8 lines of the program.
There are no strings either in Shtriped. You can take in and print out strings, but they are all represented internally as arbitrary precision integers that can only be incremented and decremented. So there's no easy way get the length of the string 10 for filling in the the square center with the right amount of spaces. I had to cobble together the function ~ that effectively computes floor(log10(N)) + 1 to find the length of N in decimal.
This could probably be golfed a bit more by rearranging where and how which variables are used, but not that much more. There's no getting around Shtriped's inherent limitations. (It was never meant to be a golfing language anyway.)
Commented code (a backslash is a comment):
@ f x \ function that calls f() x times, returns 0
 d x
 f
 @ f x
+ x y \ returns x + y
 +
  i x
 @ + y
 h x
} x y \ returns 1 if x >= y, else 0
 e 1
 i 1
 d y
 d 1
 d x
 } x y

\ declare and set up variables for the numbers 0, 2, 6, 10
e 0 \ 0 is used to help copy values via +
e 2 \ 2 is used for printing newlines
i 2
i 2
e 6 \ 6 is used for printing spaces
+ 2 2 6
+ 2 6 6
e T \ 10 is used for finding the string length of N
+ 2 2 T
+ 6 T T

e N \ declare N
t N \ and set it to what the user inputs

\ all the code from here to the last ~ is for finding the length of N as a string

e P \ P is the current power of 10 (10, 100, 1000...), starting with 10
+ T 0 P
e L \ L will be the length of N in decimal digits
i L

* \ function that returns P times 10 by adding P to itself 10 times
 e x
 *
  + P x x
 @ * T
 h x

~ \ function that increments L and multiplies P by 10 until N < P, at which point L will be the string length of N
 } N P 0 \ the 0 variable can be used as a dummy now since we don't need it anymore
 d 0
 i L
 * P \ multiply P by 10 to
 ~
~

\ helper functions for displaying the output
# \ simply prints N as a decimal integer
 p N
- \ prints a single space
 s 6
_ \ prints L spaces (L = digit length of N)
 @ - L
$ \ prints one of the central N-2 lines of the square
 #
 @ _ n
 #
 s 2

\ finally, call these functions to display the output
@ # N \ print N copies of N (top line of square)
e n \ declare n and set it to N - 2
+ N 0 n
d n
d n \ if N was 0 or 1 the program will end here, having printed nothing if 0 or just the top line if 1
s 2 \ print a newline
@ $ n \ print the central line of the square N-2 times
@ # N \ print N copies of N (bottom line of square)

\ the output always prints without a trailing newline

Seriously, 32 31 30 29 bytes
╩╜ó$╝╜Dbu╜╛*n╜¬;╛l*' *╛+╛@+n(

Try it online!
Explanation:
╩╜ó$╝╜Dbu╜╛*n╜¬;╛l*' *╛+╛@+n(
╩                              push each input to its own register
                                 (we'll call register 0 "n")
 ╜                             push n to the stack
  ó                            terminate if 0
   $╝                          push str(n) to register 1
                                 (we'll call register 1 "s")
     ╜Dbu╜╛*n                  make min(2,n) copies of s*n (the top and bottom)
                                 (this avoids an extra copy if n is 1)
             ╜¬;               push n-2 twice
                ╛l*' *         push (n-2)*len(s) spaces
                      ╛+╛@+    put s on the front and end of the string (a middle piece)
                           n   push (n-2) total copies of the middle piece
                            (  bring the top piece to the top

 C++14, 156 chars
I thought it was a pretty cool solution though obviously can not beat most other entries here.
#define f for(i=0;i++<n;c<<t);
[](string t){auto&c=cout;int n=stoi(t),i;f c<<'\n';for(i=0;++i<n-1;c<<t,c.width(~-n*size(t)+1),c.fill(0),c<<t+'\n');if(n-1)f}

Ungolfed:
#define f for ( i = 0; i++ < n; c << t ); // print top/bot row
[](string t) {
  auto& c = cout;
  int n = stoi(t), i;
  f // print first row
  c << '\n'; // kind of annoying but no way to get rid of (yes I tried
             // c << '\n'+t instead of c << t+'\n')
  for ( i = 0; ++i < n - 1; ) {
    c << t; // output the number
    // then we we get the width of necessary spaces
    c.width(~-n*size(t)+1); // Equivalent to (n-1)*size(t) + 1, but we save
                            // two bytes since ~- takes precedence over
                            // multiplication
    c.fill(0); // fill with spaces, ' ' == 0
    c << t+'\n';
   }
   if ( n-1 ) f // This if statement is dissapointing
}

And like always, to call the function use [](string t) { ... }("10");

JavaScript (ES6), 73 82 78 bytes
Saved a4 bytes thanks to @user81655
n=>(a=n[r='repeat'](n),n<2?a:a+`
${n+' '[r](n.length*(n-2))+n}`[r](n-2)+`
`+a)

Takes a string, not a number for input.
Try it online (all browsers work)

You can replace *(n-2) with *~-~-n to save a byte.

@user81655 thanks, that fixed it

@Neil thanks but that doesn't appear to save any bytes unfortunately

Sorry, I must have miscounted.

MATL,  34 29 26 bytes
:G\2<t!+gQ"@!2GVYX1GVnZ"YX

This works with current release (13.0.0) of the language/compiler
Try it online!
:            % array [1,2,...,N], where N is input, taken implicitly
G\           % modulo N. Gives [1,2,...,N-1,0]
2<           % smaller than 2? Gives [1,0,...,0,1]
t!           % duplicate, transpose
+            % addition with broadcast. Gives 2D array with nonzeros in the border
             % and zeros in the interior
gQ           % convert to logical, add 1: twos in the border, ones in the interior
"            % for each column of that array (note the array is a symmetric matrix,
             % so columns and rows are the same)
  @!         %   push column. Transpose into a row
  2GVYX      %   replace twos by the string representation of N, via regexp
  1GVnZ"YX   %   replace ones by as many spaces as length of that string, via regexp
             % end for each, implicitly
             % display stack contents, implicitly

T-SQL/SQL Server 2012+, 167 161 bytes
DECLARE @ INT = 6;

SELECT IIF(u IN(1,s),REPLICATE(s,s),CONCAT(s,REPLICATE(' ',s-2*LEN(s)),s))
FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v

Output:
666666
6    6
6    6
6    6
6    6
666666

LiveDemo
Enter desired size and click Run query to get text representation.
Please note that this demo does not display fixed-width font. So 7 is thicker than 1.

EDIT:
If we treat input as string:
DECLARE @ VARCHAR(10) = '7';

SELECT IIF(u IN(1,s),REPLICATE(s,s),s+REPLICATE(' ',s-2*LEN(s))+s)
FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s+0)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v

LiveDemo2

This is very nice, I learned how to shorten some of my other scripts a bit. Didn't know the order by 1/0 and sys.messages

on a side note.Should the declaration of input parameter really be included when counting the bytes ?

@t-clausen.dk I am not sure about counting rules, when SQL is applied but I will ask on meta and let you know.

@t-clausen.dk http://meta.codegolf.stackexchange.com/questions/9126/how-to-count-bytes-with-sql

You can save a few bytes by making s varchar(like this '6'), then you can replace concat with +.

Seems you are missing some spaces. I believe you can fix it by writing (s-2)

Nice techniques! You can use SPACE() instead of REPLICATE(' ', n) to save a bunch of bytes. Also, @t-clausen.dk is correct, your space counts fails for values of n>9.

Julia, 78 bytes
n->(s="$n";(p=println)(s^n);[p(s*" "^(n-2)endof(s)*s)for i=2:n-1];n>1&&p(s^n))

This is an anonymous function that accepts an integer and prints the ASCII rectangle to STDOUT. To call it, assign it to a variable.
Ungolfed:
function f(n)
    # Save a string version of n
    s = "$n"

    # Print the top line
    println(s^n)

    # Print each middle line
    [println(s * " "^(n-2)endof(s) * s) for i = 2:n-1]

    # Print the last line if there is one
    n > 1 && println(s^n)
end

Try it online

Ruby, 100 bytes
->n{s="";n.times{|i|s+=(i<1||i>n-2?"#{n}"*n :"#{n}#{' '*[(n-2)*n.to_s.size,0].max}#{n}")+$/};puts s}

Too bad I couldn't even manage to beat JS. Any further help golfing it down would be appreciated.
Here's a more or less ungolfed version:
def f(n)
    n.times{|num|
        if num == 0 || num == n-1
            s += "#{n}" * n
        else
            s += "#{n}"+" "*[(n-2)*n.to_s.length,0].max+"#{n}"
        end
        s += "\n"
    }
    puts s
end

You might want to assign a variable to n.to_s since you use it so much, giving you m*n for the first part and m+" "*[(n-2)*m.length,0].max+m for the second part.

I based a 75-byte version on this answer. (Javascript is currently at 78 bytes) Try it online!

Retina, 76 bytes
.+
$0$*n$0
n(?=n*(\d+))|.
$1_
\d+_
$_¶
T`d` `(?<=¶.*_.*).(?=.*_\d.*¶\d)
\`_
[empty line]

Explanation maybe comes tomorrow.
Try it online here.

It's been a while since tomorrow.

It's been more than a whole year since tomorrow.

TSQL, 112 104 bytes
DECLARE @ varchar(10)='12'

PRINT REPLICATE(@,@)+ISNULL('
'+REPLICATE(@+ISNULL(SPACE((@-2)*len(@))+@,'')+'
',@-2)+REPLICATE(@,@),'')

1. generating first line
2. adding hollow lines + line breaks
3. adding last line(when needed)

Could you add an explanation for those of us who don't know T-SQL?

@cat wrote a short explanation, and included a fiddle

Interesting, thanks! It looks like your byte count might be off: check here

@cat thanks. I was looking for a link for that. However the last line with the FROM is just declaring and assigning value to X, I heard that assigning values and declaring variables doesn't count. Please correct me if i am wrong. I tried to save a few bytes with this assignment of variables. Normal variables are prefixed with @, costing 1 extra byte for each time using it

Here is my approach. Also TSQL :)

Nice work. Save some bytes with SPACE() instead of REPLICATE(' ', n). Also, on my machine it cuts off the output text when @=63 or higher, but I'm not sure if that's your problem or a SSMS client setting.

@BradC you are right in both cases. management studio has limited output and the space thing has been adjusted. Thanks

Is it work correclty when n=1?

@mazzy yes it does - 3. adding last line(when needed)

Minkolang 0.15, 57 bytes
nd?.d1-2&N.$z01FlOz2-[lz6Z" "I2-z2-*Dz6Z$O]01F.
z[z6Z]$Of

Try it here!
Explanation
n                Read number from input
 d?.             Stop if n=0, continue otherwise
    d1-2&N.      Print 1 and stop if n=1, continue otherwise
           $z    Store top of stack in register (z, which is n)

01F                                   Gosub to second line
   lO                                 Print newline
     z2-                              Push value from register and subtract 2
        [                             Pop k and run body of for loop k times
                                      (Does not run if k <= 0)
         l                            Push a newline
          z6Z                         Push z and convert to string
             " "                      Push a space
                I2-                   Push length of stack minus 2
                   z2-                Push z minus 2
                      *               Pop b,a and push a,b
                       D              Pop k and duplicate top of stack k times
                        z6Z           Push z and convert to string
                           $O         Output whole stack as characters
                             ]        Close for loop
                              01F.    Gosub to second line and stop after returning.

z[   ]       For loop that runs z times
  z6Z        Push z and convert to string
      $O     Output whole stack as characters
        f    Return to position called from

Pyth - 26 bytes

K*QQjbm++Q**lQ;ttQQttQK
Try it online here.

@FryAmTheEggman the permalink button seems to be broken

Perl, 79 76 74 bytes
$_=$.=pop;s/./ /g;print$.x$.,$/,($.,$_ x($.-2),$.,$/)x($.-2),$.>1?$.x$.:''

Pretty straightforward. The first commandline argument is taken as the number. Place the script in a file and run with perl file.pl 1.

shift can be replaced with pop.

Perl, 62 60 58 + 2 = 60 bytes
for$.(1..$_){say$.>1&$.<$_?$_.$"x(y...c*($_-2)).$_:$_ x$_}

Requires -nlE flags:
$ perl -nlE'for$.(1..$_){say$.>1&$.<$_?$_.$"x(y...c*($_-2)).$_:$_ x$_}' <<< 5
55555
5   5
5   5
5   5
55555

With spaces added:
for$.(1..$_) {
  say(
    $. > 1 & $. < $_
      ? $_ . $"x(length$_*($_-2)) . $_
      : $_ x $_
  )
}

R, 90 bytes
x=scan();m=matrix(x,x,x);k=2:(x-1)*(x>2);m[k,k]=format("",w=nchar(x));write(m,"",n=x,s="")

This creates a matrix of x*x size and then fills with spaces of size nchar(x) . If x smaller than 2, then nothing is being filled.

I know this is a year later, but...
x=scan();m=matrix(x,x,x);m[k<--c(1,x),k]=format("",w=nchar(x));write(m,"",x,,"") is 10 bytes fewer by using negative indexing and replacing n=x,s='' with x,,''
https://tio.run/nexus/r#DYpBCsAgDAT/4imBCPVs85LSg0hLRbSQCub3NgwszDJL@cupA8bGLQ0pCkqG@VF37zMEE6on369YAM7R5J6fJKCIcUoZFzSyW8kWV9jWDw

@Giuseppe And now for something completely unreadable... save one more byte.

write("[<-"(matrix(x<-scan(),x,x),k<--c(1,x),k,gsub("."," ",x)),1,x,,"") for 72 bytes.

Pip -l, 21 bytes
Uses language features newer than the question, which is allowed per current policy; if the wording of the question is interpreted to override said policy, see 25-byte answer below.
Yq{MN++g%y>1?sMyy}MCy

Try it online!
Thanks to Luis Mendo's MATL answer for the (a+1)%n<2 trick.
Explanation
Yq reads a line from stdin and yanks it into y. Then:
{              }MCy  Map this function to each coordinate pair in a y-by-y grid
                     (Inside the function, the list of both coords is g)
   ++g                Increment both coordinates
      %y              Take them mod y
 MN     >1?           Test whether the min of the resulting list is 2 or greater
           sMy         If so, it's in the center; use len(y) spaces
              y        If not, it's an edge; use the number y
                     Print result with newlines between rows (implicit, -l flag)

Original 2016 answer, 25 bytes (plus -l flag):
Yq{MN++*a%y<2?ysX#y}MMCGy

Changelog:

MC was added more recently; at the time, I used MMCG (map-map + coordinate-grid).
There was a bug in the current interpreter that prevented using ++ on lists, so I had to do ++* (apply ++ to each element) instead.
Map has been extended: now <string1> M <string2> returns a list of len(<string2>) copies of <string1>; at the time, I used sX#y, string-repeating space by len(y).

Pyth, 37 30 bytes
J*K`QQI>Q1JV-Q2++Q*d-lJ*2lKQ;J

Try it here.
J*K`QQ                          set K to repr(input); that is, stringified
                                  set J to K repeated (input) times
      I>Q1                  ;   if input is greater than 1...
          J                     output J (stringified input times input)
           V-Q2                 do this (input - 2) times...
               ++               output the following on one line:
                 Q              the input number
                  *d-lJ*2lK     n spaces, where n = len(J) - 2*len(K)
                           Q    the input number again
                            ;   break out of everything
                             J  output J (str(input)*input) one last time,
                                  regardless of whether input > 1

Retina, 90
Again, I'm pretty sure this will be greatly golfable by the experts:
.+
$&$&$*:$&$*;
+`(\d+:):
$1$1
+`([\d+:]+;);
$1$1
T`d` `(?<=;\d+:)[^;]+(?=:\d+:;\d)
:

;
¶

Try it online.

I posted a Retina answer too, but it isn't much smaller. (Can you use ¶ instead of ; to get rid of the last stage?)

@randomra Well 80 < 90 so no argument from me :)

And if you use the pilcrow [^¶]+ is handily .+.

Pyke, 33 bytes (noncompetitive)
QD`i*Djli2*lR-k*iRi]3J"bR+2Q-*jR+

Explanation:
                                  - autoassign Q = eval_or_not(input())
QD`i*                             - Get the input multiplied by itself
Q                                 - [Q]
 D                                - [Q, Q]
  `                               - [repr(Q), Q]
   i                              - i = stack[0]
    *                             - [stack[0]*stack[1]]

     Djli2*lR-                    - Get number of spaces
     D                            - [^,^]
      j                           - j = stack[0]
       l                          - len(stack[0])
        i2*                       - i*2
           l                      - len(stack[0])
            R                     - rotate_2()
             -                    - stack[0]-stack[1]

              k*iRi               - Get middle line
              k*                  - " "*^
                iRi               - [i,^,i]

                   ]3J"bR+        - Join middle line together
                   ]3             - list(stack[:3])
                     J"           - "".join(stack[0])
                       bR+        - ^+"\n"

                          2Q-     - Get middle lines
                          2Q-*    - Q-2

                              jR+ - Add end line
                              jR+ - ^+j

Jelly, 28 bytes
Grr, can’t tell if Jelly is bad at strings, or if I’m bad at Jelly.
ŒṘ©L⁶xWẋWẋ$®W¤1¦€U'Z$$4¡j⁷ȯ⁷

Try it online.

I've been trying to adapt this for an answer, but without much luck :/

CJam, 27 bytes
ri:X,_ff{a+[0X(]&XXs,S*?}N*

Thanks to @MartinBüttner for suggesting ff. The a+[0X(]& is pretty fishy, but oh well.
Try it online!
ri:X              Read input integer and save as variable X
,_                Range, i.e. [0 1 ... X-1] and make a copy
ff{...}           Map with extra parameter, twice. This is like doing a Cartesian product
                  between two 1D arrays, but we get a nice X by X array at the end

                  For each coordinate pair,
a+                Put the two coordinates into an array
[0X(]&            Set intersection with the array [0 X-1]
X                 Push X
Xs,S*             Push a number of spaces equal to the length of X
?                 Ternary: choose one of the previous two depending on the set intersection

N*                Join X by X array with newlines

Haskell, 78 bytes
i x=unlines$take x$1#s:3#[s++(3#s>>" ")++s]++[1#s]where s=show x;z#s=[z..x]>>s

Usage example:
*Main> putStr $ i 4
4444
4  4
4  4
4444

The function >> comes in handy: <list> >> <string> makes length <list> copies of <string>, e.g. top and bottom lines for x=10 are [1..10] >> "10" -> "10101010101010101010".

71 bytes

@MaxYekhlakov: Thanks, but unfortunately your version doesn't work for 1 which shout output a single 1. Also, you return a list of strings, whereas the challenge asks for a single string. We had much stricter IO rules back in the days, flexible IO rules are a more recent thing.

Perl, 72 bytes
$_=($.=pop)-2;say for($.x$.,($..($.x$_)=~s/./ /rg.$.)x$_,$.x$.)[0..$.-1]

Relies on modern Perl features :

say 'something'

is automatically available since Perl 5.10 (simply use v5.10 or later).

str_expr =~ s/.../.../r

happily accepts to work on a rvalue (an str_expr not necessarily reduced to a scalar variable) to yield a result (the 'r' option at the end of the regex) without altering the initial str_expr.

PHP, 151 bytes
function s($n){for($r=0;$r<$n;$r++){for($c=0;$c<$n;$c++){if($r*$c&&$r!=$n-1&&$c!=$n-1){for($d=0;$d<=log10($n);$d++){echo' ';}}else{echo$n;}}echo"\n";}}

Absolute mess, need more time to optimize.  s(Number) gives you the output.

Python 3, 108 96 148 bytes
a=input()
b=c=int(a)-2 if a!="1" else 0
print(a*int(a))
while b:print(a+" "*int(len(a))*c+a);b-=1
if a!="1":print(a*int(a))

Ungolfed/explained:
number = input() # Gets a number as input
iterator = var = int(number) - 2 if number != "1" else 0 # Assigns two variables, one of them an iterator, to the number minus 2 (the amount of middle rows in the square) if the number isn't 1. If it is, it sets the vars to 0 so the while doesn't trigger.
print(number * int(number)) # Prints the top row of the square.
while iterator != 0: # Loops for the middle rows
    print(number + " " * int(len(number)) * var + number) # Prints the number, then as many spaces as needed, and the number.
    iterator -= 1 # De-increments the iterator.
if number != 1: # Makes sure the number isn't 1, because 1 should return 1.
    print(a * int(a)) # Same as the first row, it prints the bottom row.

As this is my first code-golf answer, some constructive criticism and/or suggestions would be helpful!

Use single spaces for indentation to shave off some bytes. In fact, your entire loop can be inlined: while b!=0:print(a+" "*int(len(a))*c+1);b-=1. Furthermore, while b: is equivalent to while b!=0, so that's 3 more bytes gone.

Bugfix: input 1 now prints 1, not infiniteloop (my browser really gave me some grief). This now takes tons more bytes tho.

Java 8, 280 bytes
interface A{static<T>void p(T o){System.out.print(o);}static void main(String[]a){long n=new Long(a[0]),l=a[0].length();for(long i=0;i<n;i++,p(a[0]));p("\n"+(n>1?a[0]:""));for(long j=2;j<n;j++,p(a[0])){for(long i=l*2;i<n*l;i++,p(' '));p(a[0]+"\n");}for(long i=1;i<n;i++)p(a[0]);}}

It's only about 10 times as long as the shortest answers, which is really good for Java!
Example run:
$ java A 10
10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010

Rust, 141 137 bytes
Abused some formatting stuff, otherwise this would've been a lot longer.
|i|{let f=||{for _ in 0..i{print!("{}",i)}println!("")};f();if i>1{for _ in 0..i-2{println!("{}{0:1$}",i,i.to_string().len()*(i-1))}f()}}

Unpacked:
|i| {
    let f = || {
        for _ in 0..i {
            print!("{}",i)
        }
        println!("")
    };

    f();

    if i>1 {
        for _ in 0..i-2 {
            println!("{}{0:1$}",i,i.to_string().len()*(i-1))
        }
        f()
    }
}

Playground Link

This doesn't work when I try it here.  How can I test this?

Here's a playground link so you can test it, I used a closure so you have assign that to a variable first then call it.

Oh cool.  Don't really know rust, but great answer!

Nice answer, you can try putting the variable directly inside the string println!("{i}") . Also try using clippy in rust playground(Tools>Clippy).

Powershell, 98 96 95 83 82 75 bytes
param($n)($l="$n"*$n)
if(($m=$n-2)-ge0){,"$n$(' '*"$n".Length*$m)$n"*$m
$l}

Ungolfed and explained test script:
$f = {

    param($n)
    ($l="$n"*$n)                #   let $l is a string contains N only and return this value as a first line
    $m=$n-2
    if($m-ge0){                 # if(N>1)
        $s=' '*"$n".Length*$m   #   let $s is spaces inside repeated (length of string represented of n * m)
        ,"$n$s$n"*$m            #   return $m strings contains: N, spaces and N
        $l                      #   retrun the first line again
    }

}

&$f 1
&$f 2
&$f 3
&$f 4
&$f 10

Output:
1
22
22
333
3 3
333
4444
4  4
4  4
4444
10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010

MathGolf, 28 25 19 bytes
░*k┴╜o\⌡{khí **k++p

Try it online!
Explanation
This was a fun challenge. Disclaimer: this language is younger than the challenge itself, but the methods used for this answer are not designed for this challenge in particular. I realised that I can save a byte for the 1-case, and by reducing the number of print statements.
░                     convert implicit input to string
 *                    pop a, b : push(a*b)
  k                   read integer from input
   ┴                  check if equal to 1
    ╜                 else without if
     o                print TOS without popping (handles the 1-case)
      \               swap top elements
       ⌡              decrement twice
        {             start block or arbitrary length
         k            read integer from input
          h           length of array/string without popping
           í          get total number of iterations of for loop
                      space character
             *        pop a, b : push(a*b)
              *       pop a, b : push(a*b) (this results in (n-2)*numdigits(n)*" ")
               k      read integer from input
                +     pop a, b : push(a+b)
                 +    pop a, b : push(a+b)
                  p   print with newline

@JoKing that added two bytes. I wanted to be able to use the "make each list element equal in length" operator, but I couldn't get it working as I wanted.

Vyxal, 20 bytes
ẋṅ,⇩(L⁰‹*$S↲₴,)ċ[ẋṅ,

Try it Online!
How?
ẋṅ,⇩(L⁰‹*$S↲₴,)ċ[ẋṅ,
ẋ                    # Repeat the (implicit) input the (implicit) input number of times (returns a list)
 ṅ                   # Join by nothing
  ,                  # Print with trailing newline
   ⇩(                # Loop (implicit) input minus 2 times:
     L               #  Get the length of the (implicit) input
      ⁰‹             #  Push the input minus 1
        *            #  Multiply the length by that
         $           #  Swap to make (implicit) input at top
          S          #  Convert the input to a string
           ↲         #  Pad the stringified input with leading spaces until its length is len(input) * (input - 1) calculated earlier
            ₴        #  Print this without a trailing newline
             ,       #  Print the (implicit) input with trailing newline
              )      # Close loop
               ċ[    # If the (implicit) input is not one:
                 ẋ   #  Repeat the (implicit) input the (implicit) input amount of times
                  ṅ  #  Join by nothing to make it a string
                   , #  Print with trailing newline

Pyth, 27 bytes
jsMmm?sqM*,dk,0tQ`Q*\ l`QQQ

Test suite.

05AB1E, 34 30 29 bytes
Code:
F¹}JDU,¹!#¹DÍF¹gFð}}¹J¹ÍF=}X,

Try it online!
I didn't have some kind of fancy string multiplication function, but here is the submission with the function. It's something I added after the challenge and is therefore non-competing:
26 bytes:
Code:
D×DU,¹¹Í¹g*ð×¹J¹ÍF=}¹1›iX,

Uses CP-1252 encoding.

Python 2, 70 characters
def p(i):
 k=`i`;j=i-2;h=k*i;print h+'\n'+(k+' '*j*len(k)+k+'\n')*j+h

Doesn't work for i=1.

Ruby, 79 bytes
->n{s=n.to_s
puts s*n
$><<(s+" "*s.size*(a=n-2)+s+$/)*a if n>2
$><<s*n if n>1}

Some cases print a trailing line after the last line and some do not, but the question does not disallow this.

PHP 112 114 120 bytes
<?php $z=$j=$argv[1];while($j){$i=(--$j&&$i)?$z.str_pad('',strlen($z)*($z-2)).$z:str_repeat($z,$z);echo"$i\n";}

Command line usage: php scriptname.php [n]
ideone demo
This golf uses str_repeat for the first and last row and str_pad for the rows in between.

Dyalog APL, 41 bytes
{1≥⍵:⍵⍴⍵⋄(' '≠⍕⍵/⍵)/⍕⍵⍪⍨⍵⍪⍵,⍵,⍨''⍴⍨2/⍵-2}

Python 2, 73 characters
def l(i):s=`i`;n='\n';l=i-2;b=s*i+n;print b+(s+' '*l*len(s)+s+n)*l+b*(i>1)

I believe your n='\n'; optimization is costing you one character, not saving any.

Python 3.5, 101 135 bytes:
(+34 since apparently an input of 1 should just output 1 and an input of 0 should output nothing)
def y(g):g=str(g);i=len(g);[print(g*(int(g))+('\n'+g+' '*((int(g)*i)-(i*2))+g)*(int(g)-2)+'\n'+g*int(g))if int(g)>1 else print(g*int(g))]

Prints out all the correct values for any integer input, whether in string form or not.
Sample Inputs and Outputs:
Input: y(10)

Output:

    10101010101010101010
    10                10
    10                10
    10                10
    10                10
    10                10
    10                10
    10                10
    10                10
    10101010101010101010

Input: y(1)

Output:

    1

Input: y(2)

Output:

    22
    22

Input: y(4)

Output:

    4444
    4  4
    4  4
    4444

However, for triple digit numbers, it was just too big to fit on my monitor, so I hope that comes out correct if someone else tries it. I suspect it should since all 1 and 2 digit numbers come out correctly.

Python 3, 75 characters
def q(n):s=str(n);m=n-2;print(s*n,*[s+" "*len(s)*m+s]*m,s*n*(n>1),sep="\n")

Welcome to Programming Puzzles and Code Golf. This is a great first answer, however it would be even better if you added a code explanation and breakdown as well.

Try it online! Also, as a full program this is 77 bytes.

PHP, 86 Bytes
for(;$i<$a=$argn;)echo str_pad($a>1?$a:"",($a-1)*strlen($a),$i++&&$i<$a?" ":$a)."$a
";

Try it online!

JS to ES6 compatibilized, 136 76 B
function x(a){var c='';function Q(){for(var b=0;b<a;++b)c+=a}Q();c+='\n';
for(b=2;b<a;++b){c+=a;for(let A=2;A<a;++a)c+=' ';c+=a+'\n'}Q()}

Works way smaller:
x=(a,c)=>{Q=(í,k)=>{for(;í<a;++í)c+=k}Q(0,a);c+='\n';Q(2,a+Q(2,' ')+a+'\n')}

Python 2,96 bytes
s=raw_input()
n=int(s)
for i in range(n):
 if 0<i<n-1:print s+' '*(n-2)*len(s)+s
 else:print s*n

Python 3,94 bytes
s=input()
n=int(s)
for i in range(n):
 if 0<i<n-1:print(s+' '*(n-2)*len(s)+s)
 else:print(s*n)

You accidentally left a space after the assignment to n in both answers.

Python 3, 78 bytes
N=input()
n=int(N)
m=n-2
b=N*n+"\n"
print(b+(N+" "*len(N)*m+N+"\n")*m+b*(n>1))

Try it online!
I went back and forth over multiple approaches to this (even using exec() at one point, then ditching it because it was unnecessary), but I figured out that this is the shortest Python 3 approach.

As a subroutine this is 77 bytes.

05AB1E, 16 bytes
×,<GgIÍ*ú«,}≠i×,

Try it online or verify all test cases.
Explanation:
×          # Repeat the (implicit) input the (implicit) input amount of times as string
 ,         # Pop and print this string with trailing newline
<G         # Loop the (implicit) input-2 amount of times:
  g        #  Get the length of the (implicit) input
   IÍ      #  Push the input-2
     *     #  Multiply it by the length
      ú    #  Pad the (implicit) input with that many leading spaces
       «   #  Append it to the (implicit) input
        ,  #  Pop and print it with trailing newline
 }         # Close the loop
  ≠i       # If the (implicit) input is NOT 1:
    ×      #  Repeat the (implicit) input the (implicit) input amount of times as string
     ,     #  Pop and print this string with trailing newline

I don't think I've ever used the fact that input can be implicitly as many times in a single program as this one. xD

Regenerate, 42 bytes
(($~1){$~1})((
$2 {#2}{$2-2}$2){$2-2}
$1!)

Attempt This Online!
For clarity, space is replaced with _ and newline is replaced with ¶:
(                    # Capture the first line as $1, for reuse as the last line.
    ($~1){$~1}       # Repeat N in decimal, N times. Capture N in $2 for golf,
                     # which allows referring to it as "$2" instead of "$~1" and
                     # its length as "#2" instead of "#~1".
)
(
    (
        ¶
        $2           # Output N in decimal for the left edge.
        _{#2}{$2-2}  # Output length(N)*(N-2) spaces
        $2           # Output N in decimal for the right edge.
    ){$2-2}          # Repeat the above N-2 times. This will cause a non-match
                     # if N == 1, preventing this entire block from matching,
                     # which will also prevent the top line from being repeated
                     # as the bottom line below.
    ¶
    $1               # Repeat the top line as the bottom line.
!
                     # If N == 1, the above alternative won't be able to match;
                     # do nothing here, to prevent it from triggering a top-level
                     # non-match.
)

Mathematica,116 bytes
Switch[#,0,"",1,1,_,#5<>#4[#<>#4[" ",StringLength@#*#3]<>#<>"\n",#3]<>#5&[##,#~#4~#2<>"\n"]&[ToString@#,#,#-2,Table]]&

Somewhat long, but oh well.

Oracle SQL 11.2, 106 105 115 bytes
SELECT RPAD(:1,(:1-1)*LENGTH(:1),DECODE(LEVEL,1,:1||'',:1,:1||'',' '))||:1 FROM DUAL WHERE:1>0 CONNECT BY:1>=LEVEL;

10 bytes added to manage 0

SmileBASIC, 89 bytes
INPUT N$N=VAL(N$)Q=N>1FOR I=1TO N?N$*!!N*G;" "*LEN(N$*(N-Q*2))*G;N$*(Q*G+N*!G)G=I<N-1NEXT

Common Lisp, SBCL, 151 bytes
(defun c(x)(if(< x 10)1(1+(c(/ x 10)))))(lambda(a)(format t"~:[~v{~a~:*~}~&~v@{~v<~a~;~a~>~4@*~&~}~*~v@{~a~:*~}~;1~]"(= a 1)a`(,a)(- a 2)(*(c a)a)a a))

function for counting digits adjusted to CL from Joshua's answer here
Ungolfed
(defun c(x)
    (if(< x 10) 1
    (1+ (c(/ x 10))))) ;counting digits
(lambda(a)
    (format t"~:[~v{~a~:*~}~&~v@{~v<~a~;~a~>~4@*~&~}~*~v@{~a~:*~}~;1~]"(= a 1)a`(,a)(- a 2)(*(c a)a)a a))
;~[~] checks whether agument is equal 1 (if it is equal 1 then print out only "1") - without it we would print out 1\Newline 1
;first loop: ~v{~a~:*~} - printing first line of N
;second loop: uses justification "~<~>" to output enough spaces between N's on sides
;third loop: -printing last line of N

QBIC, 61 58 bytes
;_LA|x=!A!~x=1|?A\Y=A+space$((x-2)*a)+A[x|Z=Z+A]?Z[x-2|?Y]

Explanation
;          Read A$ from the cmd line
_LA|       Take the length of A$ and assign to a
x=!A!      Cast A$ to int, assign to x
~x=1|?A    If x == 1, quit printing just the 1
\Y=A       Else, setup Y$ as the middle of the square; it starts as the literal input
  +space$( Followed by X spaces
  (x-2)*a) where X is the length of the string x the value, minus start and end
  +A       Followed by the input again
[x|        This FOR loop creates the top row
Z=Z+A]     By concatenating the input x times to itself and assigning it to Z$
?Z         Print the top row
[x-2|?Y]   Print the right amount of middle rows
           And the bottom row (Z$) is implicitly printed at EOF.

Non-competing maybe?

Perl 5, 67+2=69 bytes
Requires the flags -lp.
$@=($,=$"=$_)-2;$,x=$,;s/./ /g;$"=$".$_ x$@.$".$/;$_=$,.$/.$"x$@.$,

Has all the length of a mainstream language, and the unreadability of a more esoteric language!

Lua, 101 bytes
p,n=print,io.read()d,s=#n,n:rep(n)p(s)for i=3,n do p(n..(" "):rep(d*(n-2))..n)end p(n+0>1 and s or"")

Alternate 102 bytes:
l,n="\n",io.read()d,s=#n,n:rep(n)print(s..l..(n..(" "):rep(d*(n-2))..n..l):rep(n-2)..(n+0>1 and s or""))

101 Readable:
p,n=print,io.read()
d,s=#n,n:rep(n)
p(s)
for i=3,n do
  p(n..(" "):rep(d*(n-2))..n)
end
p(n+0>1 and s or"")

Lua naturally has a small trick here by being able to convert a number as a string (e.g. "123") into a string or a number as needed based on context. It's not 100% intelligent though as you can see in my "ternary" statement at the end for handling the 0 and 1 cases- I had to use n+0 to coax it into a number before comparing it to 1.

WC, 146 bytes
;>_0|;>_0|$-;>_0|;>=_0|[<]$'[>]$--[>]$--[>];>_0|$''_0|!$?#@3|//#;>(?[>]$-!!_0|;>@5|$''[<<<<]!!$?!$[>>>>>>];<?[>]##@3|/#)?##@10|[>>>>>]*$#?[>>>>]!$

Try it online!
Ungolfed/commented:
;>_0|;>_0|       var n, var c
$-               decrement c
;>_0|;>=_0|      var i, var len = length(X)
[<]              move to i
$'[>]            multply i by len
$--[>]$--[>]     i -= len (x2)
;>_0|$''_0|      var full = X repeated X times
!$               print full
?                reset index
#@3|             if n == 0
  //             terminate
#                end if
;>(              new function
  ?[>]           set index to 1
  $-!!_0|        decrement c and print it
  ;>@5|          var spaces
  $''[<<<<]      repeat i times
  !!$            print spaces
  ?              reset index
  !$             print n
  [>>>>>>]       move to spaces
  ;<             delete spaces var
  ?[>]           set index to 1
  ##@3|          if c != 0
    /            restart context (this function)
  #              end if
)                end function
?                reset index
##@10|           if n != 2 (10th global)
  [>>>>>]        set index to 5
  *$             call the function
#                end if
?[>>>>]          set index to 4
!$                print full

When you compile Wasp, it becomes the Water Closet

APL(NARS), 69 chars, 138 bytes
{⍵≤1:⍕⍳⍵⋄f←{⊂∊⍺/⊂⍕⍵}⋄y←((⍴⊃x←f⍨⍵)-2×⍴r←⍕⍵)f' '⋄⊃x,((⊂∊r,y,r)/⍨⍵-2),x}

test:
  g←{⍵≤1:⍕⍳⍵⋄f←{⊂∊⍺/⊂⍕⍵}⋄y←((⍴⊃x←f⍨⍵)-2×⍴r←⍕⍵)f' '⋄⊃x,((⊂∊r,y,r)/⍨⍵-2),x}
  ⎕fmt   g¨0 1 2 3 11
┌5──────────────────────────────────────────┐
│┌0┐ ┌1┐ ┌2─┐ ┌3──┐ ┌22────────────────────┐│
││ │ │1│ 222│ 3333│ 11111111111111111111111││
│└¯┘ └─┘ │22│ │3 3│ 111                  11││
│        └──┘ │333│ │11                  11││
│             └───┘ │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │1111111111111111111111││
│                   └──────────────────────┘2
└∊──────────────────────────────────────────┘

Pyth, 29 bytes
*zKszVSJ-K2p+z*J*lzdz)I>K1*zK

Try it online!
Properly handles "1" case, even if it cost me 3 more characters to do so. Still new to Pyth, and there's some interesting stuff happening with that Pyth answer that uses all the joins.
*zKsz        #input auto-assigned to z as string, assign K to int(z), and print z*K
VSJ-K2       #set J to K-2, for N in range J
p+z*J*lzdz   #print with no newline: z + (" " * len(z)) * (K - 2), print z
)I>K1*zK     #close for loop and print z*K if K greater than 1

C# (.NET Core), 146 bytes
a=>{string b=a.ToString(),s="";for(int i=0,j,k;++i<=a;s+="\n")for(j=0;++j<=a;)if(i>1&i<a&j>1&j<a)for(k=0;k++<b.Length;)s+=" ";else s+=b;return s;}

Try it online!
Ungolfed:
a => {
    string b = a.ToString(), s = "";            // initialize b (saves 4 bytes) and s (return variable)
    for(int i = 0, j, k; ++i <= a; s += "\n")   // for each row of the square
        for(j = 0; ++j <= a;)                       // for each column of the square
            if(i > 1 & i < a & j > 1 & j < a)           // if not an edge of the square
                for(k = 0; k++ < b.Length;)                 // for each digit in a
                    s += " ";                                   // add a space
            else                                        // if an edge of the square
                s += b;                                     // add the input num
    return s;                                   // output the full string

Japt, 22 bytes

_hUçU)z3
NgV gV gV gV

Try it online!
More competitive than I expected, though I wouldn't be surprised if Charcoal or something has a really short answer that just hasn't been found yet.
Explanation:

                :Empty line preserves the input as U

_hUçU)z3        :Declare a function V taking an argument Z:
_h   )          : Set the first line of Z to
    U           :  U as a string
  Uç            :  Repeated U times
      z3        : Rotate Z 90 degrees counterclockwise

NgV gV gV gV    :Main program
N               : Start with an arbitrary array (in this case [U])
 gV gV gV gV    : Apply V 4 times

It's necessary to rotate counterclockwise in V because a single-line array always ends up left-aligned when rotated, making clockwise rotations take an extra gV. The 1 extra byte for z3 instead of z was better.

Japt -R, 18 bytes
îU
U+ÕÅ+UÔÅ Õ·hJUw

Test it online!

Batch, 264 bytes
@echo off&setlocal enabledelayedexpansion&set o=&set m=
for /l %%i in (1,1,%1)do set o=!o!%1&if %%i gtr 2 set m=!m!%1
if %1 gtr 0 echo %o%&if %1 gtr 2 (for /l %%i in (0,1,9)do set m=!m:%%i= !
set/an=%1-2
for /l %%i in (1,1,!n!)do echo %1!m!%1)
if %1 gtr 1 echo %o%

Only works for numbers up to 2029 because of the length limitations of echo.


text:
Radiation softened quine
It's simple: Make a proper quine where if you remove any character, it's still a quine.
The difference between this and a radiation hardened quine is that if your program is AB, in a radiation hardened quine A would output AB, but here, A would output A.
Code golf, all standard rules, standard loopholes apply, no cheating.

Is an empty program valid?

@Loovjo No.

Does the original program need to be a quine? I.e. in the example, is it enough that A outputs A and B outputs B, or is it also necessary that AB outputs AB?

@feersum The challenge states "Make a quine where...", so AB should output AB.

@Mego I know it says that, but specifications are not always so precise, and it is not indicated in the examples.

@feersum "Make a quine" means make a quine. "The difference between this and a radiation-hardened quine..." means that the only difference is that the program with any one byte removed results in a quine, not a program that prints the original program's source. There is no ambiguity here.

><> (Fish), 145 107 bytes
This answer uses ><>'s jumping instruction to fix the problem.
!<0078*+00~..>0[!."r43a*+8a+&{ee+00&1-:&(?.~~ol?!;4b*0.0f<>0['r3d*159*+&}7a*00&1-:&(?.~~ol?!;68a*+0.0+*a58

This quine actually contains two different quine generators. It starts with some jumping logic and by default uses the left quine. If a character is removed from the jumping logic or from the left quine, the program jumps to the right quine.
You can try it here
Explanation
The code can be dissected into a few parts:
A: !<0078*+00~..>0[!.
B:              >0[!."r43a*+8a+&{ee+00&1-:&(?.~~ol?!;4b*0.
C:                                                    .0f<
D:                                                        >0['r3d*159*+&}7a*00&1-:&(?.~~ol?!;68a*+0.
E:                                                                                .0+*a58

Explanation of the different parts:

A: Jumps to the right of C. If any character is deleted from from A,
this jumps to the left of D or the right of E, triggering the second
quine.
If any character is deleted from B or C, the code is shifted 1
character to the left, causing this to jump to the left of D.
C: This code jumps to the left of B.
B: Quine #1
D: Quine #2
E: Jumps to the left of D

Explanation of the quine (with #1 as example):
Once the instruction pointer reaches either of the quines, you're certain that that quine is completely intact.
>0[!.                                       //Fix the instruction pointer's direction and empty the stack (The '!.' is a leftover from codepart A)
     "r43a*+                                //Start reading all of the code and add the '"' character to the stack
            8a+&                            //Because the quine started reading at the 19th character instead of the first, the stack has to move 18 characters.
                                            //This part saves the number 18 to the register.
                {ee+00&1-:&(?.              //Move the stack one to the left, decrease the stack by 1. If the stack is not empty yet, jump back to the start of this section.
                              ~~              //Clean the temporary variables from the stack. It should now contain the whole quine.
                                ol?!;4b*0.  //Print the first character from the stack. As long as the stack isn't empty, jump back to the start of this section.

Explanation please.

Reiterating above.

Is this clear enough?

Lenguage, 4.54×10761 bytes
It has this number of null characters:

453997365974271498471447945720930600149036031871190716908688344432973027776681259141680552038829875159204621651993092104775733418288411812715164994750890484868305218411129600012389568016974351721147925344946382782884546247102886167837964612372737300786173159265347137401863281368021545169383664534228503236761742285358985343373496184959796553930661837467682191561275123057706776367104142995491262443697167483190110516522677811931124842961701222425076750211774387637740969301686178545299089832300154448308384461700726890067468872402133010536518468336342175124002115991866466700174974019423711837589532744970385003356612639263433822126850314801275940879069069974437167102618471264140597777702065896715558989678487253830854848740247786166790545462769498303055791292

Seeing how the criterion in this challenge conflicts with the definition of a "proper quine", seriously, I think an Unary variant is going to win.
Expanded Brainfuck code:
>>+++>++++++++>+++>+++>+>+>+>+>+>+>+>+++>+>+>+>+>+>+>+>+>+++>+>+>+>+>+>+>+>+>++++++++>++++>++++++++>++++>+++++++>++>+++>+>+++>++>+++>+++>+>+>+>+>+>+>+>+>++++>++++>+++++++>+>++++>++++++++>++>+++++++>+++>++++++++>++>+++++++>+++>++++++++>++>+++++++>+++>++++++++>++>+++++++>+++>+++++>++++++++>++++>+++++++>+++++++>+>+>+++>+>+>+>++++++++>+++>+++++++>+>+++>+>+++>+>+++>+>++++++++>++++>++++++++>++++>++++++++>++++>++++>+>+++>+++>++>+++++++>+++++++>+>+>+>++++++++>+++>+>++++++++>++++>+>+++>++>+++++++>++>+++++++>++++>++++>++++++++>+++>++++++++>+++>+++>+>++++>++++>++>+++++++>+++>+++>++++++++>++++>+>+++>++>+++++++>++++>++++>+++++++>+++>+++>+++>+++>++++++++>++++>++++>+>+++>+>+++>++>+++++++>+++++++
[
    [->+>+<<]
    >>>>[<<[->+<]>>[-<<+>>]>]
    <<[-[->+<]+>]+++
    [[->>+<<]<]<
]
+>+>+>+
[>]+++>++
[
    [<].
    >[-]>[-]>[-]>[-]
    <+[<<++++++++>>->+>-[<]<]
    ++++++++>++++++++>+++++++>>
]
.

If one character is removed from the Lenguage program, the last character becomes a <, which causes the program to print exactly one less character.

How did you manage to find that fixed point? (Or alternatively, how does the Brainfuck code work?)

@MartinBüttner The first big loop copies and encodes the data in the form of ">+++..." (and reverses it). The other big loop print the data as an integer in unary. It's not that complicated but is long only because it's Brainfuck.

Oh right, so it's just like a plain Brainfuck quine, but with a different decoding function?

@MartinBüttner Somewhat. But half of the program is the "decoding function".

It seems you could use a similar technique to construct answers of arbitrary score for http://codegolf.stackexchange.com/q/57257/8478 (although how exactly that works would depend on the answer to my latest comment).

@lirtosiast It is a true quine. The first line in the Brainfuck code encodes the rest. (Or the number of whole segments consisting of 8^155 null characters encodes other null characters, if you prefer that.)

@MartinBüttner Technically, it says the program should work only when exactly n characters are removed, but not less, so you can get an arbitrary n. But still, it says least program_length^2/n wins, where a long program like this doesn't have much advantage.

@jimmy23013 yeah, the scoring was changed after my comment.

@MartinBüttner Last time I checked it I believed that it must also work if less than n characters are removed. In that case it can only get a score of 3, or the final character would become an unmatched ], making the program invalid.

How would one include a payload on this quine?

@lirtosiast Insert code before the second loop in the Brainfuck code. The memory is the Brainfuck code with the instructions represented by 1 to 8, with some delimiters.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Weight balancing problem
Have you ever wondered, when doing shopping, how to pack your products into 2 bags you're carrying so that a total weight would be distributed among them as evenly as possible?
Your task is to write a function, that takes a list of positive numbers (lets say integers for simplicity) as an input. It should return two lists, which:

Together contain all of the input elements
The difference of their sums is as close to zero as possible.

The order of returned lists, and their elements is irrelevant.
Here are a couple of test cases:
[] -> [[], []]
[1] -> [[1], []]
[1, 1] -> [[1], [1]]
[1, 2, 1] -> [[1, 1], [2]]
[4, 2, 3, 1] -> [[1, 4], [2, 3]]
[3, 8, 1, 5] -> [[1, 8], [3, 5]]

Hi, and welcome to Programming Puzzles and Code Golf! Unfortunately, this problem is essentially a duplicate of this array partition problem, which itself is a duplicate of this subset sum problem, so I've marked it thus.

Edit: I didn't realise my dupe vote was binding, so I've undone my vote in order to let the community decide whether the additional optimisation goal (difference closest to zero rather than exactly zero) is different enough.

Just found this question, which might be an actual dupe this time?

Damn. Didn't see that one. I guess mine is a dupe after all.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Unslice a string
Given an input of a list of slices of a string, output the original string.
Each slice will be given as a list of length 2, containing the start position
of the slice (an integer ≥0) and the slice itself. If your language does not
support arrays of arbitrary types, you may also take this as a struct or
similar, or simply a string consisting of the number, a space, and then the
slice.
The order of the two elements of each slice is up to you. Furthermore, if you
choose to use the representation of slices as a length-2 array, you may take
input as either a 2-dimensional array or a single flat array. Finally, the
integer representing position may be either zero-indexed or one-indexed (all
the examples here are zero-indexed).
The input will always be sufficient to determine the entire string up to the
highest position given. That is, there will be no "holes" or "gaps." Therefore,
the output must not contain any extra trailing or leading characters (other
than the typical optional trailing newline). The input will always be
consistent, and no slices will conflict with each other.
Since this is code-golf, the shortest code in bytes will win.
Test cases:
In                                                Out
-----------------------------------------------------------
[[2, "CG"], [0, "PP"], [1, "PC"]]               | PPCG
[[0, "foobarbaz"]]                              | foobarbaz
[[0, "foobar"], [6, "baz"]]                     | foobarbaz
[[2, "ob"], [5, "rba"], [0, "fooba"], [8, "z"]] | foobarbaz
[[0, "fo"], [0, "fooba"], [0, "foobarbaz"]]     | foobarbaz

Is there any restrictions on what characters the string will contain?

@GamrCorps Nope, no special restrictions.

Are there any restrictions on the length of the output string?

@Mego None aside from natural limits imposed by memory/storage.

HA! This is the undo mechanism in my text editor :D

Can there be trailing spaces in the slices?

@Nᴮᶻ Solutions should be able to support slices containing any printable ASCII characters.

Jelly, 10 9 bytes
Ḣ0ẋ;Fµ€o/

Try it online!
How it works
Ḣ0ẋ;Fµ€o/  Main link. Input: A (list of pairs)

     µ€    Convert the chain to the left into a link, and apply it to each pair.
Ḣ          Pop the first element.
 0ẋ        Yield a list of that many zeroes.
   ;F      Concatenate the list of zeroes with the popped, flattened pair.
       o/  Reduce the generated lists by logical OR.
           Since all characters are truthy, this overwrites zeroes with characters,
           but never characters with zeroes.

Python 2, 49 bytes
lambda l:`map(max,*[' '*n+s for n,s in l])`[2::5]

First, lines up the strings by padding their offsets with spaces (shown as underscores for clarity)
[[2, "CG"], [0, "PP"], [1, "PC"]]

__CG
PP
_PC

Then, uses map to zip and take the maximum of each column, which ignores the smaller values of spaces (the smallest printable character) and Nones where some strings were too short.
__CG
PP
_PC

PPCG

Finally, ''.join to a string using the [2::5] trick.

Whats the 2::5 trick? How does that join a string? Isn't that every 5th index starting at 2?

@RobertFraser See here.

JavaScript (ES6), 61 bytes
a=>a.map(([o,s])=>[...s].map(c=>r[o++]=c),r=[])&&r.join``

Edit: Saved 4 bytes thanks to @edc65.

a=>a.map(([o,s])=>[...s].map(c=>r[o++]=c),r=[])&&r.join`` saves 4 bytes

Haskell, 57 bytes
import Data.List
map snd.sort.nub.(>>= \(n,s)->zip[n..]s)

Usage example:
*Main> map snd.sort.nub.(>>= \(n,s)->zip[n..]s) $ [(2,"CG"),(0,"PP"),(1,"PC")]
"PPCG"

How it works: make pairs of (index,letter) for every letter of every slice, concatenate into a single list, remove duplicates, sort by index, remove indices.

Perl, 25
Added +2 for -lp
Get the input from STDIN, e.g.
perl -lp slices.pl
2 CG
0 PP
1 PC

(Close with ^D or ^Z or whatever closes STDIN on your system)
slices.pl:
/ /;$r|=v0 x$`.$'}{*_=r

Wouldn't the null byte instead of v0 save you two bytes (because you could also omit the space before the x)? Edit: Hm, no, when I tried it, I got Can't locate object method "x" via package "2" (or whatever the number is on my first line) for some reason.

Only names like C variables can be unquoted literals. So v0 is the shortest way to get \0 (or a \0 between quotes for a tie in this case due to the extra space)

Factor, 64 40 bytes
[ sbuf new tuck '[ _ copy ] assoc-each ]

Attempt This Online!
This answer makes use of the fact you can set arbitrary indices of a growable sequence (in this case a string buffer) and the sequence will expand appropriately with default values. copy copies one sequence to another starting at an index; a perfect fit for this problem.

MATL, 15 bytes
''i"@Y:Y:tn:b+(

Works with current version (13.0.0) of the language/compiler.
Input is with curly braces and single quotes. (Curly braces in MATLAB/MATL define cell arrays, which are lists that can have contents of arbitrary, possibly different types.) The test cases are thus:
{{2, 'CG'}, {0, 'PP'} {1, 'PC'}}
{{0, 'foobarbaz'}}
{{0, 'foobar'}, {6, 'baz'}}
{{2, 'ob'}, {5, 'rba'}, {0, 'fooba'}, {8, 'z'}}
{{0, 'fo'}, {0, 'fooba'}, {0, 'foobarbaz'}}

Try it online!
''      % push empty string. This will be filled with the slices to produce the result
i       % take input: cell array of cell arrays. For example: {{0, 'foobar'}, {6, 'baz'}}
"       % for each (1st-level) cell
  @     %   push that cell. Example: {{0, 'foobar'}}
  Y:    %   unpack (1st-level) cell, i.e. push its contents. Example: {0, 'foobar'}
  Y:    %   unpack (2nd-level) cell array: gives number and substring. Example: 0, 'foobar'
  tn:   %   duplicate substring and generate vector [1,2,...,n], where n is length of
        %   current substring (in the example: 6)
  b+    %   add input number that tells the position of that substring within the whole
        %   string (in the example: 0; so this gives [1,2,...,6] again)
  (     %   assign substring to the total string, overwriting if necessary. Note that
        %   MATL uses 1-indexing
        % end for each
        % implicit display

This answer's a bute!

J, 24 bytes
[:u:3>./@u:-@(+#&>){.&>]

Try it online!
alternative, 24 bytes
[:u:[:>./(#&0@[,3 u:])&>

Try it online!

DUP, 14 bytes
[0[$;$][,1+]#]

Try it here.
Anonymous lambda. Usage:
2"CG"0"PP"1"PC"[0[$;$][,1+]#]!

NOTE: DUP does not really have arrays, so I hope this input format is okay.
Explanation
Well, DUP's string comprehension is... interesting. Strings are stored as a series of number variables, each of which holds a charcode from the string. Something like 2"CG" works as pushing 2 to the stack, then creating a string with index starting from 2.
Because these indexes are really variables, they can be overwritten. That's what the input is really doing: overriding! Try pressing Step on the interpreter site to get a better idea for this. After this, we get an unsliced string.
This is where the outputting comes in.
[            ] {lambda}
 0             {push 0 to the stack as accumulator}
  [   ][   ]#  {while loop}
   $;$         {duplicate, get var at TOS value, see if that var is defined}
        ,1+    {if so, output charcode at TOS and increment accumulator}

Hooray for DUP!

PHP, 146 chars
Note: Evaling user input is always a good idea.
Golfed
<?$a=[];$f=0;eval("\$b={$argv[1]};");foreach($b as$d){$f=$d[0];$e=str_split($d[1]);foreach($e as$c){$a[$f++]=$c;}}ksort($a);echo join('',$a)."\n";

Ungolfed
<?php
$array = array();
$p = 0;
eval("\$input = {$argv[1]};");
foreach($input as $item)
{
    $p = $item[0];
    $str = str_split($item[1]);
    foreach($str as $part)
    {
        $array[$p++] = $part;
    }
}
ksort($array);
echo join('', $array)."\n";
?>

You can see that I'm just writing the input into an array with the specific key each char has and then output it all.
Tests
php unslice.php '[[0, "foobar"], [6, "baz"]]' -> foobarbaz
php unslice.php '[[2, "CG"], [0, "PP"], [1, "PC"]]' -> PPCG
php shorten.php unslice.php -> Shortened script by 107 chars. :D

"Evaling user input is never a good idea" Code Golf is about worst-practices :D

$a[$f]=$c;$f++; I don't know PHP but can't this be $a[$f++]=c; ?

Ill try it.. :D

@cat Thx mate, shorted it by 3 chars. :D

Ruby, 40 bytes
->a{s=""
a.sort.map{s[_1,_2.size]=_2}
s}

Attempt This Online!

Japt -mh, 15 12 bytes
P=úUÎÄ hUÎUÌ

Try it
P=úUÎÄ hUÎUÌ     :Implicit map of each array U in input array W
P=               :Assign to P (an empty string, initially)
  ú              :Right pad P with spaces to length
   UÎ            :  First element of U
     Ä           :  Add 1
       h         :Replace the characters starting at index
        UÎ       :  First element of U
          UÌ     :  With last element of U
                 :Implicit output of last element of resulting array

Vyxal s, 6 bytes
∩÷-∩vG

Try it online! (test suite) Input as a list of [num, str].
Explanation:
∩÷-∩vG # whole program

∩      # transpose (num and str in their own groups)
 ÷     # split into each item
  -    # prepend '-' to str num amount of times (vectorises)
   ∩   # transpose
    v  # for each item (i.e. vectorise next element)
     G # get max char
       # s flag: concatenate list into a string, then print

Python, 91 bytes.
Saved 1 byte thanks to cat.
It's a bit long. I'll golf it down more in a bit.
def f(x):r={j+i:q for(i,s)in x for j,q in enumerate(s)};return"".join(map(r.get,sorted(r)))

Seriously, 48 bytes
,`i@;l(;)+(x@#@k`M;`i@X@M`MMu' *╗`iZi`M`i╜T╗`MX╜

Seriously is seriously bad at string manipulation.
Try it online!
Explanation:
,`i@;l(;)+(x@#@k`M;`i@X@M`MMu' *╗`iZi`M`i╜T╗`MX╜
,                                                 get input
 `              `M;                               perform the first map and dupe
                   `     `MM                      perform the second map, get max element
                            u' *╗                 increment, make string of that many spaces, save in reg 0
                                 `   `M           third map
                                       `    `M    fourth map
                                              X╜  discard and push register 0

Map 1:
i@;l(;)+(x@#@k
i@;l            flatten, swap, dupe string, get length
    (;)+(       make stack [start, end, str]
         x@#@k  push range(start, end), explode string, make list of stack

Map 2:
i@X@M
i@X     flatten, swap, discard (discard the string)
   @M   swap, max (take maximum element from range)

Map 3:
iZi  flatten, zip, flatten (make list of [index, char] pairs)

Map 4:
i╜T╗  flatten, push reg 0, set element, push to reg 0

In a nutshell, this program makes a string with n spaces, where n is the minimum length the string can be based on the input. It determines the index in the result string of each character in each slice, and sets the character in the result string at that index to the character.

Python, 119 115 bytes
def f(x,s=""):
 x.sort()
 for e in x:
  a=e[0];b=e[1]
  for i,c in enumerate(b):
   if len(s)<=(i+a):s+=c
 return s

Test cases

Japt, 16 bytes
ñÎrÈ+S hYÌYg)x}P

Try it
Explanation:
ñÎrÈ+S hYÌYg)x}P
               P # Starting with an empty string X
  r           }  # For each item Y in:
ñ                #  Input sorted by
 Î               #  The first item in each sub-array
   È             # Apply the following to X:
    +S           #  Add a space to the end
       h    )    #  Overwrite:
          Yg     #   Starting index is the first item in Y
        YÌ       #   New characters are the last item in Y
             x   #  Trim any leftover whitespace

Unfortunately h wraps its index, so attempting to write new characters at the end of a string with it instead writes them back at the start.

Sorry, @KamilDrakari, I'd missed that.

QBasic, 127 114 bytes
INPUT n
FOR j=1TO n
INPUT i
LINE INPUT s$
l=LEN(s$)
e=LEN(r$)-i-l
r$=r$+SPACE$(e*(e<0))
MID$(r$,i+1,l)=s$
NEXT
?r$

You can try it at Archive.org. The input format is: first, the number of slices; then, for each slice, the (0-based) index and the string on separate lines. Here's what running the first test case would look like:
? 3
? 2
CG
? 0
PP
? 1
PC
PPCG

Explanation
INPUT n

Input the number of slices as n.
FOR j = 1 TO n
...
NEXT

Loop n times:
INPUT i

Input the starting index of the next slice as i.
LINE INPUT s$

Input the contents of the slice as s$. LINE INPUT is used to make sure that any printable ASCII character can be included in the input; if characters like , and " could be excluded, the two input statements could be combined as INPUT i,s$, saving 11 bytes.
l = LEN(s$)

Store the length of the slice as l.
e=LEN(r$)-i-l

The result string is stored in r$ (initially empty by default). If merging this slice would extend r$ beyond its current length, the number of characters we would need to add is given by i plus l minus the current length of r$. Calculate this amount, negated (see below for why), and store it as e.
r$ = r$ + SPACE$(e * (e < 0))

Pad r$ as necessary by appending spaces to it. Comparison operators in QBasic return -1 for true and 0 for false. Thus, if e < 0, we append -e spaces; otherwise, we append 0 spaces.
MID$(r$, i + 1, l) = s$

Overwrite l characters of r$, starting at index i + 1 (since MID$ uses 1-based indexing), with the contents of s$.
PRINT r$

After the loop finishes, print the final value of r$.

Pyth, 13 bytes
meSd.Tm+*;hde

Test suite
Takes input as a list of elements of the structure [index, string]. Outputs a list of characters.
Explanation:
meSd.Tm+*;hde   | Full code
meSd.Tm+*;hdedQ | with implicit variables
----------------+------------------------------------------------
      m       Q | Map over the input:
       +    ed  |  Prepend the string with
        *;hd    |   <index> spaces
    .T          | Ragged transpose
meSd            | Take the lexicographically last element of each

05AB1E (legacy), 7 bytes
ε`ú}ζ€à

Output as a list of characters.
Try it online or verify all test cases.
Explanation:
Uses the legacy version of 05AB1E instead of the new one for two reasons:

The zip/transpose builtins work on a list of strings, whereas the new version would require a list of lists of characters.
The minimum/maximum builtins work on characters (using their codepoint), which doesn't work in the new version.

ε     # Map over each pair of the (implicit) input-list:
 `    #  Pop the pair and push both values separated to the list
  ú   #  Pad the string with the integer amount of leading spaces
}ζ    # After the map: zip/transpose the strings, swapping rows/columns, using a default
      # space " " filler if strings are of unequal length
  €   # Map over each string
   à  #  Only leave its maximum character
      # (after which the resulting list of characters is output implicitly)

CJam, 26 bytes
q~{~0c*\+}%{.{s\s|}}*e_0c-

Try it online!. Takes input in form [["CG"2]["PP"0]["PC"1]].
Explanation:
q~           Read and eval input

{~0c*\+}%    Convert input strings into workable format
{      }%     Map onto each input
 ~            Evaluate
  0c          Null character
    *\+       Multiply by input number and concat to string

{.{s\s|}}*   Combine strings
{       }*    Fold array
 .{    }       Vectorize, apply block to corresponding elements of arrays
   s\s         Convert elements to strings
      |        Set Union

e_0c-        Remove null characters

R, 181 bytes
n=nchar;m=matrix(scan(,'raw'),ncol=2,byrow=T);w=rep('',max(n(m[,2])+(i<-strtoi(m[,1]))));for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],''));cat("",w,sep="")

With line breaks:
n=nchar
m=matrix(scan(,'raw'),ncol=2,byrow=T)
w=rep('',max(n(m[,2])+(i<-strtoi(m[,1]))))
for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],''))
cat("",w,sep="")

Works in R Gui (single line one, or sourcing for the multi-line one) but not in ideone, example:
> n=nchar;m=matrix(scan(,'raw'),ncol=2,byrow=T);w=rep('',max(n(m[,2])+(i<-strtoi(m[,1]))));for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],''));cat("",w,sep="")
1: 2 ob 5 rba 0 fooba 8 z
9:
Read 8 items
foobarbaz

Note on the input method:

or simply a string consisting of the number, a space, and then the slice.

I assume I comply with this part of the spec with this kind of input, it can be given on multiple lines, this has no impact as long as there a blank line to end the input.
I think 2 chars can be saved by removing the +1 and using 1 based indexing but I started with challenge input.

C, 110 bytes
c,i,j;char s[99];main(){while(~scanf("%i ",&i))for(;(c=getchar())>10;s[i++]=c);for(;s[j]>10;putchar(s[j++]));}

This program takes the slice after its index in one line of input each.
Ungolfed:
c,i,j;char s[99];

main(){
    while(~scanf("%i ",&i))
        for(;(c=getchar())>10;s[i++]=c);
    for(;s[j]>10;putchar(s[j++]));
}

Test on ideone.com

Lua, 113 bytes
z=loadstring("return "..io.read())()table.sort(z,function(a,b)return a[1]<b[1]end)for a=1,#z do print(z[a][2])end

This is probably some of the more secure code I've written. The idea is simple. The user will enter an array formatted as so: {{1, "1"}, {3, "3"}, {2, "2"}} and then the table will be sorted by the first index and the second index will be printed.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
That's a prime... almost
If you've ever learned about primes in math class, you've probably have had to, at one point, determine if a number is prime. You've probably messed up while you were still learning them, for example, mistaking 39 for a prime. Well, not to worry, as 39 is a semiprime, i.e., that it is the product of two primes.
Similarly, we can define a k-almost prime as being the product of k prime numbers. For example, 40 is the 4th 4-almost prime; 40 = 5*2*2*2, the product of 4 factors.
Your task is to write a program/function that accepts two integers n and k as input and output/return the nth k-almost prime number. This is a code-golf, so the shortest program in bytes wins.
Test cases
n, k => output
n, 1 => the nth prime number
1, 1 => 2
3, 1 => 5
1, 2 => 4
3, 2 => 9
5, 3 => 27

Miscellaneous
You have to generate the primes yourself by any means other than a simple closed form, if such a closed form exists.

Check your math in your first example: 40 is not equal to 52222.

@GamrCorps Ah, yes, thank you.

How do you define the nth k-almost prime? What determines what order the k-almost primes are in?

@GamrCorps Similar to how you determine the nth prime: you can generate a list of the first n numbers with k prime factors, sorted from least to greatest, and take the last member in that list.

I don't think your expression for f in terms of f[n,1] is correct, since the lists of almost-primes contain odd numbers (e.g. the last two examples, which are not expressible as the product of a power of two and a prime).  (And it also says that f[n,1] == 2*f[n,1].)

@2012rcampion Oh, my mistake. It was a simple observation that was not founded by proof.

Why is a simple closed form banned?

Your last paragraph doesn't make sense. There's no known closed form for the problem you are asking, and in fact there are proofs that such a closed form does not exists (when taking operations from certain sets of operations [e.g. surely no polynomial exists that produces all primes ]).

@Bakuriu I don't know much about the proofs. I was merely trying to ban trivial solutions.

What I'm saying is that there aren't trivial solutions. Just say that it must work with 1 <= n <= 100 and 1 <= k <= 10, so that storing the solutions in a table is infeasible and you are done.

Pyth, 9 bytes
e.fqlPZQE

Explanation
          - autoassign Q = eval(input())
     PZ   -      prime_factors(Z)
    l     -     len(^)
   q   Q  -    ^ == Q
 .f     E -  first eval(input()) of (^ for Z in range(inf))
e         - ^[-1]

Try it here!
Or try a test suite!

Brachylog, 9 bytes
Beating @sundar by using half as much bytes
{~l~ḋ}ᶠ⁽t

Explanation
                    --  Input like [n,k]
{    }ᶠ⁽            --      Find the first n values which
   ~ḋ               --          have a prime decomposition
 ~l                 --          of length k
        t           --      and take the last one

Try it online!

Jelly, 9 bytes
ÆfL=³
ç#Ṫ

Try it online!
How it works
Ç#Ṫ    Main link. Left input: k. Right input: n.

Ç      Apply the helper link to k, k + 1, k + 2, ... until...
 #       n matches are found.
  Ṫ    Retrieve the last match.

ÆfL=³  Helper link. Left argument: k (iterator)

Æf     Yield the prime factors of k.
  L    Compute the length of the list, i.e., the number of prime factors.
   =³  Compare the result with k (left input).

I'm not aware of any encoding that can save these 9 characters as 9 bytes.

Jelly uses a custom encoding that represents the 256 character it understands with single bytes.

Pyke (commit 29), 8 bytes (noncompetitive)
.fPlQq)e

Explanation:
         - autoassign Q = eval_or_not(input())
.f    )  - First eval_or_not(input) of (^ for i in range(inf))
  P      -    prime_factors(i)
   l     -   len(^)
     q   -  ^==V
    Q    -   Q
       e - ^[-1]

Julia, 84 78 59 57 bytes
f(n,k,i=1)=n>0?f(n-(sum(values(factor(i)))==k),k,i+1):i-1

This is a recursive function that accepts two integers and returns an integer. The approach here is to check the sum of the exponents in the prime factorization against k.
Ungolfed:
function f(n, k, i=1)
    # We initialize a counter i as a function argument.

    # Recurse while we've encountered fewer than n k-almost primes
    if n > 0
        # If the sum of the exponents in the prime factorization of i is
        # equal to k, there are k prime factors of i. We subtract a boolean
        # from n, which is implicitly cast to an integer, which will
        # decrement n if i is k-almost prime and leave it as is otherwise.
        return f(n - (sum(values(factor(i))) == k), k, i + 1)
    else
        # Otherwise we return i-1 (i will have been incremented one too
        # many times, hence the -1)
        return i - 1
    end
end

Vyxal, 8 bytes
λǐL⁰=;ȯt

Try it Online!
λ    ;ȯt # Nth number where
 ǐL      # Prime factor length
   ⁰=    # Equal to input

Brachylog, 18 bytes
,1{hH&t<NḋlH;N}ⁱ⁽t

Try it online!
                      Implicit input, say [5, 3]
,1                    Append 1 to the input list. [5, 3, 1]
  {           }ⁱ⁽     Repeat this predicate the number of times given by
                        the first element of the list (5),
                        on the rest of the list [3, 1]
   hH&                Let's call the first element H
      t<N             There is a number N greater than the second element
         ḋ            Whose prime factorization's
          l           length
           H          is equal to H
            ;N        Then, pair that N with H and let that be input for
                      the next iteration
                 t    At the end of iterations, take the last N
                      This is implicitly the output

Sidef, 21 bytes
nth_almost_prime(n,k)

Mathematica, 56 51 bytes
Last@Select[Range[2^##],PrimeOmega@#==n&/.n->#2,#]&

Warning: This is theoretical. Do not run for any values>4. Replace 2^## with a more efficient expression.

This doesn't work for n=1.

Also since PrimeOmega[1] evaluates to 0, &&#>1 is redundant.

Mathematica, 53 49 Bytes
Cases[Range[2^(#2+#)],x_/;PrimeOmega@x==#2][[#]]&

Generates a list of integers based on a loose upper bound. PrimeOmega counts the prime factors with multiplicities, the k-almost prime Cases are taken from the list, and the nth member of that subset is returned.

2^(0+##), or just 2^## works.

@CatsAreFluffy Try 2^Sequence[1,2] to see why the latter fails.

Haskell, 88 bytes
Can probably be golfed a lot more, as I'm still a newbie to Haskell. The function q returns the number of factors of its argument, and f uses that to get take the nth element of a list made from all numbers that have k factors.
q n|n<2=0|1>0=1+q(div n ([x|x<-[2..],mod n x<1]!!0))
f n k=filter(\m->q m==k)[1..]!!n-1

MATL, 14 bytes
:YqiZ^!XpSu1G)

Try it on MATL Online
:               % Take first input n implicitly, make range 1 to n
 Yq             % Get corresponding prime numbers (1st prime to nth prime)
   i            % Take the second input k
    Z^          % Take the k-th cartesian power of the primes list
                % (Getting all combinations of k primes)
      !Xp       % Multiply each combination (2*2*2, 2*2*3, 2*2*5, ...)
         Su     % Sort and unique
           1G)  % Take the n-th element of the result

Python 3, 100 bytes
This is a very simple brute force function. It checks every number starting from 2 with sympy's factorint function until it has found n k-almost primes, at which point, the function returns the nth of these.
import sympy
def a(n,k):
 z=1;c=0
 while c<n:z+=1;c+=(sum(sympy.factorint(z).values())==k)
 return z

Ungolfed:
I use sum(factorint(a).values()) because factorint returns a dictionary of factor: exponent pairs. Grabbing the values of the dictionary (the exponents) and summing them tells me how many prime factors there are and thus what k this k-almost prime is.
from sympy import factorint
def almost(n, k):
    z = 1
    count = 0
    while count < n:
        z += 1
        if sum(factorint(a).values()) == k:
            count += 1
    return z

Python 2, 76 bytes
f=lambda n,k,p=2,c=0:c==k if p>n else f(n,k,p+1,c)if n%p else f(n/p,k,p,c+1)

Try it online!


text:
ASCII dank star
Input description
A string (for best results, all characters should be printable and be the same width).
Output description
A character star following the pattern:
0  0  0
 1 1 1
  222
0123210
  222
 1 1 1
0  0  0

where 0, 1 ... are subsequent characters of the string. The output does not necessarily have to be one string - printing the star char by char into the console is fine.
Example
>> star('overflow')
>>
o      o      o
 v     v     v
  e    e    e
   r   r   r
    f  f  f
     l l l
      ooo
overflowolfrevo
      ooo
     l l l
    f  f  f
   r   r   r
  e    e    e
 v     v     v
o      o      o

I think "a string" should be a little more clear, do you mean a string consisting of only printable ASCII?

I think "a string" is sufficient. Of course, for best results you probably want to avoid tabs or other characters that would distort the shape of the output, but that doesn't mean you can't include them. Still, I updated the description for clarity.

It's less a question of whether that gives the nicest results but of whether answers have to support it. Some languages might have to use somewhat different code if e.g. non-ASCII (Unicode) characters have to be supported as well. Likewise, some code might be shorter if we can assume that unprintables won't appear (specifically linefeeds).

Whether or not you can print all characters is irrelevant. If you can make your code shorter, even if it limits you from printing certain characters (like Unicode), then so be it. I think that's the spirit of code-golfing anyway. As long as your program supports common characters, it's fine. If it doesn't, then I don't think the challenge specification is the problem.

Canvas, 13 10 bytes
⤢：⁸／ｎ！ｎ↔┼┼

Try it here!
Explanation
⤢:⁸/n!n↔++
⤢          join input with newlines
 :         duplicate it
  ⁸        push the input again
   /       make a diagonal out of it
    n      overlap the two
     !     transpose that result
      n    overlap with the first duplicated one
       ↔   mirror it horizontally
        ++ quad-palindromize without changing characters

05AB1E, 15 12 bytes
gI¨„+×Λ1Iθ8Λ

Try it online.
Explanation:
g             # Push the length of the (implicit) input-string
 I            # Push the input-string again
  ¨           # Remove its last character
   „+×        # Push string "+×"
      Λ       # Use the Canvas builtin with these three arguments
              # (after which the result is output immediately as result)
       1      # Push 1
        Iθ    # Push the last character of the input
          8   # Push 8
           Λ  # Use the Canvas builtin with these three arguments again,
              # writing on top of the previous Canvas result
              # (after which the result is output immediately as result)

The Canvas Builtin uses three arguments to draw a shape:

Character/string to draw: the input minus its last character in this case
Length of the lines we'll draw: the length of the input in this case
The direction to draw in: the "+×", which translates to directions [0,4,4,0,2,6,6,2,1,5,5,1,3,7,7,3], where each digit represents a certain direction:

7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

So the +×/[0,4,4,0,2,6,6,2,1,5,5,1,3,7,7,3] in this case translates to the directions \$[↑,↓,↓,↑,→,←,←,→,↗,↙,↙,↗,↘,↖,↖,↘]\$.
Here a step-by-step explanation of how it draws for example input abcd with these steps (with the other two Canvas arguments being 4 and "abc"):
Step 1: Draw 4 characters ("abca") in direction 0↑:
a
c
b
a

Step 2: Draw 4-1 characters ("bca") in direction 4↓:
a
b
c
a

Step 3: Draw 4-1 characters ("bca") in direction 4↓:
a
b
c
a
b
c
a

Step 4: Draw 4-1 characters ("bca") in direction 0↑:
a
b
c
a
c
b
a

Step 5: Draw 4-1 characters ("bca") in direction 2→:
a
b
c
abca
c
b
a

Etc., resulting in:
a  a  a
 b b b
  ccc
abcacba
  ccc
 b b b
a  a  a

After which we replace the middle a with the last character of the input-string with 1Iθ8Λ, where Λ is another call of the Canvas builtin with the options: 1 for the length; Iθ is the last character of the input; and 8 to reset the direction-option back to the start (although in this case, the 8 could also be any of the eight directions 0-7 for the same result, since it already ended at the center anyway).

Charcoal, 7 4 bytes
Ｐ*⮌Ｓ

Try it online! (Link to the verbose version.)

Pyth, 37 bytes
jKm:*;t*2lz[dtlzt_d)*3@zdtlz)pzt_zj_K

Try it here!

APL (Dyalog Unicode), 74 49 45 bytesSBCS
{⍵@(⌈x÷2)∘⍉∘(⌽⍵@(2/¨⍳x))⍣2⊢''⍴⍨2⍴x←≢⍵}(⊢,1↓⌽)

Try it online!
-11 thanks to ovs
Explanation:
{⍵@(⌈x÷2)∘⍉∘(⌽⍵@(2/¨⍳x))⍣2⊢''⍴⍨2⍴x←≢⍵}(⊢,1↓⌽)
                                      (⊢,1↓⌽) ⍝ turn "abc" into "abcba"
{                                x←≢⍵}        ⍝ x is the length of that string (passed as an argument)
                           ''⍴⍨2⍴             ⍝ Generate a blank string of x times x
                        ⍣2⊢                   ⍝ Do twice:
 ⍵@(⌈x÷2)∘⍉∘(⌽⍵@(2/¨⍳x))                      ⍝ Update our blank string with our argument (the mirrored string):
              ⍵@(2/¨⍳x)                       ⍝ Add our element horizontally, replace with our (mirrored) argument
            (⌽         )                      ⍝ Rotate vertically
          ⍉∘                                  ⍝ Transpose (double rotate, vertical and horizontal)
 ⍵@(⌈x÷2)∘                                    ⍝ Add our argument vertically to the string

Since we're doing these transposes twice, we'll have rotated our image on all four quadrants.

You can save a few bytes by assigning ≢⍵ to a variable: Try it online!

Removing some duplicated code and two minor changes (' ' -> '' and 2×⍨x -> 2×x) bring this down to 58 bytes.

Thank you, integrated :)

43 bytes

Updated,thanks again

PowerShell Core, 155 99 bytes
param($a)($r=0..($l=$a.length-2)|%{" "*$_+(,$a[$_]*3-join" "*($l-$_))})
$a+-join$a[$l..0]
$r[$l..0]

Try it online!
56 bytes saved thanks to @mazzy!
Explanation
# Build an array containing the top of the star
($r=0..($l=$a.length-2)|%{" "*$_+(,$a[$_]*3-join" "*($l-$_))})
# Prints the middle line
$a+-join$a[$l..0]
# Prints the array with the top of the star reversed
$r[$l..0]

write-host?! Try it online!

golfed a little Try it online!

@mazzy Wow, I overlooked so many obvious improvements and you added lots of smart changes. Thanks!

Uiua, 38 37 36 bytes
⊏⊙⊂⍥(⍉⊂⇌↘1.)2⊞(×↥⊙⊃=↥=1↧,,).+1⇡⧻,@ ⇌

-2 thanks to chunes.
Draws a quadrant, then replicates it.
Since we count from 0, not 1, we need a +1 / -1, otherwise the center would be 0 as well (because multiplying the maximum of 0 and 0 is... 0), and it'd get transformed to a space.
Explanation:
⊏⊙⊂⍥(⍉⊂⇌↘1.)2⊞(×↥⊙⊃=↥=1↧,,).+1⇡⧻,@ ⇌
                                   ⇌ # reverse the input string
                                 @   # put a space on the stack
                                ,    # over: copy the string back to the top of the stack
                              ⇡⧻     # range 1..length
                            +1       # add 1 so it's 1-indexed
                           .         # duplicate
             ⊞(           )          # for each combination (of the duplicates), this gives us a matrix row:column
                        ,,           # copy the 2 top values on the stack
                     =1↧             # is the minimum 1?
                 ⊙                   # store this result, temporarily remove it from the stack to...
                  ⊃                  # ...fork: do both operations to the same elements on the stack
                    ↥                # maximum
                   =                 # equal
                ↥                    # maximum of this fork
               ×                     # times the stored result
                                     # We now have the first quadrant
   ⍥(      )2                        # do twice
          .                          # copy the quadrant
        ↘1                           # drop the first element (because the middle would be duplicated otherwise)
       ⇌                             # reverse it (needs to be mirror)
      ⊂                              # append the quadrant with the mirror
     ⍉                               # transpose it so the pattern works on both sides
 ⊙                                   # store this result, temporarily remove it from the stack to...
  ⊂                                  # join the string with the space
⊏                                    # index into the strings with our matrix, zero being the empty space we just appended

Try it online!

⊃(=|=1↧|↥) can be ⊙⊃=↥=1↧,, for -1.

Edited, thanks :)

-1 more by rearranging some things.

Perl, 97 93 + 2 = 95 bytes
$i=y///c-2;push@a,map{$"x$j++.$_.($"x$i--.$_)x2}/.(?!$)/g;say for@a,s/.$//r.reverse,reverse@a

Requires -nlE flags:
$ perl -nlE'$i=y///c-2;push@a,map{$"x$j++.$_.($"x$i--.$_)x2}/.(?!$)/g;say for@a,s/.$//r.reverse,reverse@a' <<< 'overflow'
o      o      o
 v     v     v
  e    e    e
   r   r   r
    f  f  f
     l l l
      ooo
overflowolfrevo
      ooo
     l l l
    f  f  f
   r   r   r
  e    e    e
 v     v     v
o      o      o

Ungolfed:
$i=y///c-2;
push @a, map{
  $" x $j++ .
  $_ .
  ($" x $i-- . $_)x2
} /.(?!$)/g;
say for @a, s/.$//r.reverse, reverse@a

Seriously, 57 bytes
╩╜#dXΣR;╝;lr;R3Z`i' *;(;;))@(((@)' *;)kΣ`M;R@k`'
j`Mi╛╜+@

Yes, that newline is supposed to be there. Yes, Seriously still sucks at string manipulation. Hexdump (reversible with xxd -r):
00000000: cabd 2364 58e4 523b bc3b 6c72 3b52 335a  ..#dX.R;.;lr;R3Z
00000010: 6069 2720 2a3b 283b 3b29 2940 2828 2840  `i' *;(;;))@(((@
00000020: 2927 202a 3b29 6be4 604d 3b52 406b 6027  )' *;)k.`M;R@k`'
00000030: 0a6a 604d 69be bd2b 40                   .j`Mi..+@

I'll update this with an explanation once I finish writing it up. It's kinda long.

ES6, 153 bytes
s=>[...a=(t=[...s.slice(0,-1)]).map((c,i)=>(a=Array(t.length).fill` `,a[i]=c,a.join``+c+a.reverse().join``)),s+t.reverse().join``,...a.reverse()].join`\n`

Ungolfed:
function star(s) {
    r = [];
    h = s.length - 1;
    for (i = 0; i < h; i++) {
        a = [...' '.repeat(h)];
        a[i] = s[i];
        a = a.concat(s[i]).concat(a.reverse());
        r.push(a.join(''));
    }
    return r.concat(s + [...s.slice(0,h)].reverse().join('')).concat(r.reverse()).join("\n");
}

Alternative solution, also 153 bytes:
s=>[...a=(t=[...s].reverse().slice(1)).map((c,i)=>(a=Array(l+l+1).fill` `,a[i]=a[l]=a[l+l-i]=c,a.join``),l=t.length),s+t.join``,...a.reverse()].join`\n`

Ungolfed:
function star(s) {
    r = [];
    h = s.length - 1;
    for (i = 0; i < h; i++) {
        a = [...' '.repeat(h + h + 1)];
        a[i] = s[i];
        a[h] = s[i];
        a[h + h - i] = s[i];
        r.push(a.join(''));
    }
    return r.concat(s + [...s].reverse().slice(1).join('')).concat(r.reverse()).join("\n");
}

Note: The \n inside `s is a literal newline character.

Vyxal, 22 bytes
Ṫƛ¥n꘍⁰L‹↲$+&›;$Jvømøm⁋

Try it Online!
Ṫ                      # String[:-1]
 ƛ           ;         # Map...
  ¥n꘍                  # Prepend (register) spaces
     ⁰L‹↲              # Justify to the left by correct spacing
         $+            # Append the correct letter
           &›          # Increment the register
              $J       # Append the input value
                vøm    # Palindromise each
                   øm  # Palindromise
                     ⁋ # Join by newlines

Japt -R, 18 bytes
¬ÔËiDúEÃhU Ômê û ê

Try it
¬ÔËiDúEÃhU Ômê û ê     :Implicit input of string U                                 > "1234"
¬                      :Split                                                      > ["1","2","3","4"]
 Ô                     :Reverse                                                    > ["4","3","2","1"]
  Ë                    :Map each D at 0-based index E
   i                   :  Prepend
    DúE                :    D right-padded with spaces to length E                 > ["4","3","2 ","1  "]
       Ã               :End map                                                    > ["44","33","2 2","1  1"]
        hU             :Replace the first element with U                           > ["1234","33","2 2","1  1"]
           Ô           :Reverse                                                    > ["1  1","2 2","33","1234"]
            m          :Map
             ê         :  Palindromise                                             > ["1  1  1","2 2 2","333","1234321"]
               û       :Centre pad each with spaces to the length of the longest   > ["1  1  1"," 2 2 2 ","  333  ","1234321"]
                 ê     :Palidromise                                                > ["1  1  1"," 2 2 2 ","  333  ","1234321","  333  "," 2 2 2 ","1  1  1"]
                       :Implicit output joined with newlines

Python 3, 123 bytes
def f(s):n=len(s);o=[((s[i]+" "*(n-i-2))*2+s[i]).center(2*n)for i in range(n-1)];print("\n".join(o+[s+s[-2::-1]]+o[::-1]))

Haskell, 72 bytes
f(h:t)|_:s<-' '<$t,d<-s++h#s=(h:d)#zipWith(#)d(f t)
f x=[x]
s#t=s:t++[s]

Try it online!
Defines f :: String -> [String].

J, 39 38 37 bytes
(' ',|.){~[:(>.*=+.1=<.)"0/~#\.,1}.#\

Try it online!
Consider over:
First imagine a table of coordinates like:
┌───┬───┬───┬───┬───┬───┬───┐
│4 4│4 3│4 2│4 1│4 2│4 3│4 4│
├───┼───┼───┼───┼───┼───┼───┤
│3 4│3 3│3 2│3 1│3 2│3 3│3 4│
├───┼───┼───┼───┼───┼───┼───┤
│2 4│2 3│2 2│2 1│2 2│2 3│2 4│
├───┼───┼───┼───┼───┼───┼───┤
│1 4│1 3│1 2│1 1│1 2│1 3│1 4│
├───┼───┼───┼───┼───┼───┼───┤
│2 4│2 3│2 2│2 1│2 2│2 3│2 4│
├───┼───┼───┼───┼───┼───┼───┤
│3 4│3 3│3 2│3 1│3 2│3 3│3 4│
├───┼───┼───┼───┼───┼───┼───┤
│4 4│4 3│4 2│4 1│4 2│4 3│4 4│
└───┴───┴───┴───┴───┴───┴───┘

For each element, ask "Are they equal or does either equal one" =+.*e.,?  The answer will be 1 if true, 0 otherwise.  Multiply that answer by the max of the two numbers >.*:
4 0 0 4 0 0 4
0 3 0 3 0 3 0
0 0 2 2 2 0 0
4 3 2 1 2 3 4
0 0 2 2 2 0 0
0 3 0 3 0 3 0
4 0 0 4 0 0 4

Now just index into the original input, reversed, with a space prepended (' ',|.){~:
o  o  o
 v v v
  eee
overevo
  eee
 v v v
o  o  o

APL (Dyalog), 36 bytes
{(' ',⌽⍵)[1+∘.(⌈×=∨1=⌊)⍨(⌽,1∘↓)⍳≢⍵]}

Try it on APLgolf!
This takes the same approach as Jonah's J answer.
(⌽,1∘↓)⍳≢⍵ turns 'over' into the array 4 3 2 1 2 3 4.
Applying ∘.(⌈×=∨1=⌊)⍨ makes a table of \$(\alpha,\omega) \mapsto \max(\alpha,\omega) \times [\alpha=\omega \vee 1=\min(\alpha,\omega)]\$
4 0 0 4 0 0 4
0 3 0 3 0 3 0
0 0 2 2 2 0 0
4 3 2 1 2 3 4
0 0 2 2 2 0 0
0 3 0 3 0 3 0
4 0 0 4 0 0 4

And then we add 1 and index into (' ',⌽⍵).

APL(Dyalog Unicode), 49 47 bytes SBCS
{(⊢⍪1↓⊖)(⊢,0 1↓⌽)⍵@(2/¨⍳a)⊢⍵@a⊢⍉⍵@a⊢''⍴⍨2/a←≢⍵}

Try it on APLgolf!
A dfn submission which takes the string as right argument.
-2 borrowing from Ven's answer.

Python 3.8 (pre-release), 111 bytes
def f(s):l=len(s);r=range(1-l,l);[print("".join([" ",s[~max(i,-i,j,-j)]][i*j**3==j*i**3]for i in r))for j in r]

Try it online!
How it works :

s[~max(i,-i,j,-j)] with j the number of the line and i the number of the column  create this pattern

aaaaaaa
abbbbba
abcccba
abcdcba
abcccba
abbbbba
aaaaaaa

The condition i*j**3==j*i**3 is True exactly if i = 0 or j = 0 or i = ±j with j the line and i the column. This create this shape:

X  X  X
 X X X
  XXX
XXXXXXX
  XXX
 X X X
X  X  X

[" ", <char> ][ <condition> ] will print the char if the condition is true and will print " " otherwise. The result is then :

a  a  a
 b b b
  ccc
abcdcba
  ccc
 b b b
a  a  a

"".join(... for i in r) will concatenate the previous values to form a line
[print(...)for j in r] will print the line for each line

Perl 5 -F, 73 + 2 = 75 bytes
Scored by system in place at time of question.
pop@F;say$_,reverse+(map{say$;=$"x$b.$_.($"x($#F-$b++).$_)x2;$;,$/}@F),@F

Try it online!

C (gcc), 121 120 118 bytes
-3 byte thanks to @ceilingcat
main(n,v,i,j)char**v;{for(i=n=strlen(*++v);--i>-n;puts(""))for(j=-n;++j<n;)putchar(i-j&&i+j&&i*j?32:n[~abs(i|j)+*v]);}

Try it online!

YASEPL, 111 bytes
=i=1'=f$2=b®1-=t$b=g$`9@!$b-=t!f$5`1!m¥i,1!v$b-i-!s;" ",i~#m;" ",v~#m~#m<!+g}f,t+]7!1~!`2-2!m¥i,1~!+[2>s=g-|9`7