| Bytes | Lang | Time | Link |
|---|---|---|---|
| 088 | AWK | 250929T180050Z | xrs |
| 029 | 05AB1E | 160220T135856Z | Adnan |
| 042 | Regenerate | 220714T195044Z | Deadcode |
| 020 | Vyxal | 220415T014950Z | naffetS |
| 264 | Batch | 220413T231244Z | Youserna |
| 016 | 05AB1E | 200929T103136Z | Kevin Cr |
| 018 | Japt R | 181127T185907Z | Oliver |
| 022 | Japt | 181127T153331Z | Kamil Dr |
| 146 | C# .NET Core | 181127T142043Z | Meerkat |
| 019 | MathGolf | 181005T110029Z | maxb |
| 096 | Python 2 | 181005T111134Z | Vedant K |
| 021 | Pip l | 160418T041026Z | DLosc |
| 078 | Python 3 | 181005T183844Z | JosiahRy |
| 029 | Pyth | 181005T175318Z | Tryer |
| 138 | APLNARS | 181005T104804Z | user5898 |
| 075 | Powershell | 181004T150653Z | mazzy |
| 104 | TSQL | 160418T150143Z | t-clause |
| 076 | JS to ES6 compatibilized | 170805T180411Z | ffffffff |
| 146 | WC | 170617T020002Z | Jaggler3 |
| 086 | PHP | 170506T112508Z | Jör |
| nan | Perl 5 | 170506T002207Z | Chris |
| 101 | Lua | 170503T181151Z | Blab |
| 058 | QBIC | 170216T201253Z | steenber |
| 151 | Common Lisp | 170216T192716Z | user6516 |
| 089 | SmileBASIC | 170202T193331Z | 12Me21 |
| 161 | TSQL/SQL Server 2012+ | 160506T211802Z | lad2025 |
| 075 | Python 3 | 160506T184928Z | cdlane |
| 026 | MATL | 160220T022913Z | Luis Men |
| 137 | Rust | 160404T172614Z | Aceeri |
| 115 | Oracle SQL 11.2 | 160404T082345Z | Jeto |
| 156 | C++14 | 160404T070418Z | STDQ |
| 135 | Python 3.5 | 160404T035524Z | R. Kap |
| 026 | Pyth | 160220T161435Z | Maltysen |
| nan | Python 3 | 160305T142850Z | AAM111 |
| 280 | Java 8 | 160305T170221Z | user4594 |
| 073 | Python 2 | 160304T190443Z | BookOwl |
| 041 | Dyalog APL | 160302T185543Z | Adá |
| 317 | Shtriped | 160220T014826Z | Calvin |
| 079 | Ruby | 160221T053255Z | afuous |
| nan | PHP 112 | 160224T192826Z | FuzzyTre |
| 151 | PHP | 160224T164308Z | ricdesi |
| 072 | Perl | 160224T075847Z | Franck P |
| 090 | R | 160221T170324Z | David Ar |
| 078 | Haskell | 160221T103238Z | nimi |
| 029 | Seriously | 160220T021057Z | user4594 |
| 076 | Retina | 160220T220230Z | randomra |
| nan | Perl | 160220T191525Z | Andreas |
| 074 | Perl | 160220T164000Z | Kenney |
| 078 | JavaScript ES6 | 160220T015324Z | Downgoat |
| 023 | Jolf | 160220T023650Z | a spaghe |
| 070 | Python 2 | 160220T170350Z | SumnerHa |
| 027 | CJam | 160220T143430Z | Sp3000 |
| 033 | Pyke | 160220T132339Z | Blue |
| 028 | Jelly | 160220T132829Z | lynn |
| 027 | Pyth | 160220T061107Z | lirtosia |
| 090 | Retina | 160220T055924Z | Digital |
| 100 | Ruby | 160220T031041Z | Aearnus |
| 116 | Mathematica | 160220T031839Z | Calculat |
| 057 | Minkolang 0.15 | 160220T021518Z | El'e |
| 030 | Pyth | 160220T022315Z | Doorknob |
| 078 | Julia | 160220T020846Z | Alex A. |
AWK, 88 bytes
$0{for(s=$0$0RS;i++<g=$0-2;t=$0sprintf("%*s",length*g,X)$0RS t)s=$0s;print 1~$0?1:s t s}
05AB1E, 34 30 29 bytes
Code:
F¹}JDU,¹!#¹DÍF¹gFð}}¹J¹ÍF=}X,
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.
Regenerate, 42 bytes
(($~1){$~1})((
$2 {#2}{$2-2}$2){$2-2}
$1!)
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.
)
Vyxal, 20 bytes
ẋṅ,⇩(L⁰‹*$S↲₴,)ċ[ẋṅ,
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
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.
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
Japt, 22 bytes
_hUçU)z3
NgV gV gV gV
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.
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;}
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
MathGolf, 28 25 19 bytes
░*k┴╜o\⌡{khí **k++p
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
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)
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
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:
MCwas added more recently; at the time, I usedMMCG(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 oflen(<string2>)copies of<string1>; at the time, I usedsX#y, string-repeating space bylen(y).
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))
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.
Pyth, 29 bytes
*zKszVSJ-K2p+z*J*lzdz)I>K1*zK
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
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
└∊──────────────────────────────────────────┘
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
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)
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')}
WC, 146 bytes
;>_0|;>_0|$-;>_0|;>=_0|[<]$'[>]$--[>]$--[>];>_0|$''_0|!$?#@3|//#;>(?[>]$-!!_0|;>@5|$''[<<<<]!!$?!$[>>>>>>];<?[>]##@3|/#)?##@10|[>>>>>]*$#?[>>>>]!$
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
PHP, 86 Bytes
for(;$i<$a=$argn;)echo str_pad($a>1?$a:"",($a-1)*strlen($a),$i++&&$i<$a?" ":$a)."$a
";
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.
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.
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
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
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
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
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")
MATL, 34 29 26 bytes
:G\2<t!+gQ"@!2GVYX1GVnZ"YX
This works with current release (13.0.0) of the language/compiler
: % 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
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()
}
}
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
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");
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, 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!
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
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)
Dyalog APL, 41 bytes
{1≥⍵:⍵⍴⍵⋄(' '≠⍕⍵/⍵)/⍕⍵⍪⍨⍵⍪⍵,⍵,⍨''⍴⍨2/⍵-2}
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
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]
This golf uses str_repeat for the first and last row and str_pad for the rows in between.
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.
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.
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.
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".
Seriously, 32 31 30 29 bytes
╩╜ó$╝╜Dbu╜╛*n╜¬;╛l*' *╛+╛@+n(
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
Retina, 76 bytes
.+
$0$*n$0
n(?=n*(\d+))|.
$1_
\d+_
$_¶
T`d` `(?<=¶.*_.*).(?=.*_\d.*¶\d)
\`_
[empty line]
Explanation maybe comes tomorrow.
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 $_
)
}
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.
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)
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
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
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.
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
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⁷ȯ⁷
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)
:
;
¶
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
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.
Minkolang 0.15, 57 bytes
nd?.d1-2&N.$z01FlOz2-[lz6Z" "I2-z2-*Dz6Z$O]01F.
z[z6Z]$Of
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, 37 30 bytes
J*K`QQI>Q1JV-Q2++Q*d-lJ*2lKQ;J
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
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