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

56 Answers 56

1
\$\begingroup\$

Pyth, 27 bytes

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

Test suite.

\$\endgroup\$
1
\$\begingroup\$

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:

Non-competing version (26 bytes)

Code:

D×DU,¹¹Í¹g*ð×¹J¹ÍF=}¹1›iX,

Uses CP-1252 encoding.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Dyalog APL, 41 bytes

{1≥⍵:⍵⍴⍵⋄(' '≠⍕⍵/⍵)/⍕⍵⍪⍨⍵⍪⍵,⍵,⍨''⍴⍨2/⍵-2}
\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
  • \$\begingroup\$ I believe your n='\n'; optimization is costing you one character, not saving any. \$\endgroup\$ – cdlane May 6 '16 at 18:45
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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')}
\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
  • \$\begingroup\$ You accidentally left a space after the assignment to n in both answers. \$\endgroup\$ – JosiahRyanW Oct 5 '18 at 18:27
1
\$\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\$
  • \$\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 '18 at 11:35
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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")
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – wizzwizz4 May 6 '16 at 19:23
0
\$\begingroup\$

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

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

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.
\$\endgroup\$
  • \$\begingroup\$ Non-competing maybe? \$\endgroup\$ – Erik the Outgolfer May 6 '17 at 10:19
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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

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
└∊──────────────────────────────────────────┘
\$\endgroup\$
0
\$\begingroup\$

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

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.

\$\endgroup\$
0
\$\begingroup\$

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

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.

\$\endgroup\$
0
\$\begingroup\$

Japt -R, 18 bytes

îU
U+ÕÅ+UÔÅ Õ·hJUw

Test it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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