62
\$\begingroup\$

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!
\$\endgroup\$
3
  • 21
    \$\begingroup\$ The square for n=10 looks more square than for n=5. Hooray, non-square fonts! \$\endgroup\$
    – nneonneo
    Feb 20, 2016 at 19:04
  • 1
    \$\begingroup\$ May we take the integer as a string? \$\endgroup\$
    – Adám
    Mar 2, 2016 at 18:42
  • 2
    \$\begingroup\$ @Nᴮᶻ Yes you may \$\endgroup\$ Mar 2, 2016 at 19:10

60 Answers 60

16
\$\begingroup\$

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
\$\endgroup\$
8
\$\begingroup\$

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
\$\endgroup\$
0
6
\$\begingroup\$

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");

\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ How did you generate the hexdump? \$\endgroup\$ Feb 24, 2016 at 15:20
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ I used xxd. You can reverse it with xxd -r. \$\endgroup\$ Feb 24, 2016 at 16:00
5
\$\begingroup\$

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)

\$\endgroup\$
4
  • \$\begingroup\$ You can replace *(n-2) with *~-~-n to save a byte. \$\endgroup\$
    – Neil
    Feb 20, 2016 at 11:40
  • \$\begingroup\$ @user81655 thanks, that fixed it \$\endgroup\$
    – Downgoat
    Feb 20, 2016 at 18:05
  • 6
    \$\begingroup\$ @Neil thanks but that doesn't appear to save any bytes unfortunately \$\endgroup\$
    – Downgoat
    Feb 20, 2016 at 18:05
  • \$\begingroup\$ Sorry, I must have miscounted. \$\endgroup\$
    – Neil
    Feb 20, 2016 at 18:52
5
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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

\$\endgroup\$
7
  • \$\begingroup\$ 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 \$\endgroup\$ May 6, 2016 at 21:50
  • \$\begingroup\$ on a side note.Should the declaration of input parameter really be included when counting the bytes ? \$\endgroup\$ May 6, 2016 at 22:02
  • \$\begingroup\$ @t-clausen.dk I am not sure about counting rules, when SQL is applied but I will ask on meta and let you know. \$\endgroup\$
    – lad2025
    May 7, 2016 at 9:16
  • 1
    \$\begingroup\$ You can save a few bytes by making s varchar(like this '6'), then you can replace concat with +. \$\endgroup\$ May 7, 2016 at 11:25
  • 1
    \$\begingroup\$ Seems you are missing some spaces. I believe you can fix it by writing (s-2) \$\endgroup\$ May 7, 2016 at 17:16
4
\$\begingroup\$

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

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Value Ink
    Apr 18, 2016 at 5:43
  • \$\begingroup\$ I based a 75-byte version on this answer. (Javascript is currently at 78 bytes) Try it online! \$\endgroup\$
    – benj2240
    Mar 2, 2018 at 23:52
4
\$\begingroup\$

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.

\$\endgroup\$
2
  • 7
    \$\begingroup\$ It's been a while since tomorrow. \$\endgroup\$ Apr 18, 2016 at 5:23
  • \$\begingroup\$ It's been more than a whole year since tomorrow. \$\endgroup\$
    – Leaky Nun
    May 9, 2017 at 7:26
4
\$\begingroup\$

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)
\$\endgroup\$
9
  • \$\begingroup\$ Could you add an explanation for those of us who don't know T-SQL? \$\endgroup\$
    – cat
    Apr 18, 2016 at 15:54
  • \$\begingroup\$ @cat wrote a short explanation, and included a fiddle \$\endgroup\$ Apr 18, 2016 at 17:17
  • \$\begingroup\$ Interesting, thanks! It looks like your byte count might be off: check here \$\endgroup\$
    – cat
    Apr 18, 2016 at 17:34
  • \$\begingroup\$ @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 \$\endgroup\$ Apr 18, 2016 at 19:02
  • 1
    \$\begingroup\$ @mazzy yes it does - 3. adding last line(when needed) \$\endgroup\$ Oct 5, 2018 at 9:32
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ shift can be replaced with pop. \$\endgroup\$ Feb 20, 2016 at 18:41
3
\$\begingroup\$

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 $_
  )
}
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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,,'' tio.run/nexus/r#DYpBCsAgDAT/… \$\endgroup\$
    – Giuseppe
    May 5, 2017 at 20:13
  • \$\begingroup\$ @Giuseppe And now for something completely unreadable... save one more byte. \$\endgroup\$
    – JayCe
    May 23, 2018 at 19:20
  • \$\begingroup\$ write("[<-"(matrix(x<-scan(),x,x),k<--c(1,x),k,gsub("."," ",x)),1,x,,"") for 72 bytes. \$\endgroup\$
    – J.Doe
    Oct 5, 2018 at 8:40
3
\$\begingroup\$

Pyth - 26 bytes


K*QQjbm++Q**lQ;ttQQttQK

Try it online here.

\$\endgroup\$
1
  • \$\begingroup\$ @FryAmTheEggman the permalink button seems to be broken \$\endgroup\$
    – Maltysen
    Feb 20, 2016 at 17:33
3
\$\begingroup\$

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).
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I posted a Retina answer too, but it isn't much smaller. (Can you use instead of ; to get rid of the last stage?) \$\endgroup\$
    – randomra
    Feb 20, 2016 at 22:03
  • \$\begingroup\$ @randomra Well 80 < 90 so no argument from me :) \$\endgroup\$ Feb 20, 2016 at 22:06
  • \$\begingroup\$ And if you use the pilcrow [^¶]+ is handily .+. \$\endgroup\$
    – randomra
    Feb 20, 2016 at 22:08
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ I've been trying to adapt this for an answer, but without much luck :/ \$\endgroup\$
    – Sp3000
    Feb 20, 2016 at 13:40
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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".

\$\endgroup\$
2
  • \$\begingroup\$ 71 bytes \$\endgroup\$ Oct 5, 2018 at 14:10
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – nimi
    Oct 5, 2018 at 15:56
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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 answer, some constructive criticism and/or suggestions would be helpful!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – user45941
    Mar 5, 2016 at 16:26
  • \$\begingroup\$ Bugfix: input 1 now prints 1, not infiniteloop (my browser really gave me some grief). This now takes tons more bytes tho. \$\endgroup\$
    – AAM111
    Mar 5, 2016 at 22:03
2
\$\begingroup\$

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

\$\endgroup\$
4
  • \$\begingroup\$ This doesn't work when I try it here. How can I test this? \$\endgroup\$
    – Riker
    Apr 4, 2016 at 17:46
  • \$\begingroup\$ 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. \$\endgroup\$
    – Aceeri
    Apr 4, 2016 at 17:48
  • \$\begingroup\$ Oh cool. Don't really know rust, but great answer! \$\endgroup\$
    – Riker
    Apr 4, 2016 at 17:49
  • \$\begingroup\$ Nice answer, you can try putting the variable directly inside the string println!("{i}") . Also try using clippy in rust playground(Tools>Clippy). \$\endgroup\$
    – Saphereye
    Apr 14, 2022 at 4:20
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ @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. \$\endgroup\$
    – maxb
    Oct 5, 2018 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.