21
\$\begingroup\$

Task

Given one non-whitespace printable character, make a 3x3 square representation of that input. For example, if the input is #, then the output is:

###
# #
###

Rules

  • The output format is strict, although a trailing newline is allowed. It means that the space in the middle is required, and also that the two newline characters separating the three lines are required.

Testcases

Input: #

Output:

###
# #
###

Input: A

Output:

AAA
A A
AAA

Input: 0

Output:

000
0 0
000

Scoring

This is . Shortest answer in bytes wins.

\$\endgroup\$
  • 2
    \$\begingroup\$ The fact that the size is fixed allows for some optimization. Answers form the linked challenge will probably not be competitive here. So I don't think it's a duplicate \$\endgroup\$ – Luis Mendo May 11 '17 at 14:33
  • 12
    \$\begingroup\$ I was the one who downvoted, for it for being a simple, boring challenge. I'm normally a fan of easy challenges, as they're a good place for new golfers to start but this just feels too easy. \$\endgroup\$ – Shaggy May 11 '17 at 14:56
  • 32
    \$\begingroup\$ @Ayoungcoder It is a perfectly valid reason to downvote a challenge. \$\endgroup\$ – Sriotchilism O'Zaic May 11 '17 at 14:59
  • 2
    \$\begingroup\$ @Shaggy: In terms of difficulty, there's difficulty to write the program, and difficulty to golf the program. This program is easy to write, but I'm not so sure it's easy to golf it. \$\endgroup\$ – user62131 May 11 '17 at 15:33
  • 5
    \$\begingroup\$ In my opinion, this is a good challenge for people who are just getting started with code golfing. It's good to have a mix of difficulties. Overloading on any one type will be to the detriment of some part of the community. So, I'm glad this challenge was written. \$\endgroup\$ – isaacg May 13 '17 at 6:22

71 Answers 71

30
\$\begingroup\$

Charcoal, 5 3 bytes

B³S

Try it online! Edit: Saved 40% thanks to @carusocomputing. Explanation:

B   Draw a box
³   3×3 (second dimension is implicit if omitted)
S   Using the input character
\$\endgroup\$
  • 3
    \$\begingroup\$ I feel like this is cheating...>_> \$\endgroup\$ – HyperNeutrino May 11 '17 at 14:50
  • 14
    \$\begingroup\$ Then, of course, B³S to cheat the living crap outta this. \$\endgroup\$ – Magic Octopus Urn May 11 '17 at 14:51
  • 1
    \$\begingroup\$ Why would this be cheating? @carusocomputing and neil his anwser seems right to me \$\endgroup\$ – Luc H May 11 '17 at 14:53
  • 1
    \$\begingroup\$ @Ayoungcoder "cheating" as in "seems cheap" not as in "literal cheating"; the code has a built-in for "print a box of dimensions n using character s", the shortest code for this challenge being: 1. Read input. 2. Define dimension. 3. Print box. The answer to this challenge logically won't be below 2 bytes if input is implicit. \$\endgroup\$ – Magic Octopus Urn May 11 '17 at 14:54
  • 2
    \$\begingroup\$ @carusocomputing Ah, the irony - the implicit square behaviour annoyed me in my answer to Visualize the Euclidean algorithm again. \$\endgroup\$ – Neil May 11 '17 at 14:56
48
\$\begingroup\$

Carrot, 11 bytes

###
# #
###

Try it online!

The program is in caret-mode, where #s are replaced with the input.

\$\endgroup\$
  • 26
    \$\begingroup\$ The feeling when a program which looks completely invalid at first is actually perfectly valid. \$\endgroup\$ – Erik the Outgolfer May 11 '17 at 16:01
  • 3
    \$\begingroup\$ @EriktheOutgolfer ever heard of Perl? \$\endgroup\$ – NoOneIsHere Aug 11 '17 at 4:45
19
\$\begingroup\$

Python 2, 32 bytes

lambda s:s+s.join(s+'\n \n'+s)+s

Try it online!
For s='a' : the middle s+'\n \n'+s generates a\n \na and s.join turns it in aa\na a\naa (bold as are the ones that .join adds), because .join accepts a string as an iterable, then it is surrounded with the two missing characters

\$\endgroup\$
  • \$\begingroup\$ How does this add the characters to the middle line? Could you explain the answer please? \$\endgroup\$ – Notts90 May 12 '17 at 13:26
  • 1
    \$\begingroup\$ @Notts90 added an explanation c: \$\endgroup\$ – Rod May 12 '17 at 13:50
  • \$\begingroup\$ thanks I didn't know .join could iterate a string. \$\endgroup\$ – Notts90 May 12 '17 at 13:55
  • \$\begingroup\$ This works in Python 3 too. Very cool BTW. (Also, using the same method 3*c+c.join('\n \n')+3*c ties at 32.) \$\endgroup\$ – Jonathan Allan May 13 '17 at 13:49
15
\$\begingroup\$

MATL, 5 bytes

3Y6*c

Try it online!

Explanation

3Y6   % Push predefined literal: [true true true; true false true; true true true]
*     % Implicitly input a character. Multiply element-wise by its code point
c     % Convert to char. Implicitly display. Char 0 is displayed as space
\$\endgroup\$
  • 1
    \$\begingroup\$ that was quick! didnt expect a 5 byte to come that fast. \$\endgroup\$ – Luc H May 11 '17 at 14:26
  • 2
    \$\begingroup\$ Code-golfing languages, you know... ¯\_(ツ)_/¯ \$\endgroup\$ – Luis Mendo May 11 '17 at 14:27
  • 11
    \$\begingroup\$ Of course, because why wouldn't you have a predefined literal for [true true true; true false true; true true true] \$\endgroup\$ – PunPun1000 May 11 '17 at 14:48
  • 11
    \$\begingroup\$ @PunPun1000 That's actually used a lot (together with convolution) as it's the standard 8-connectivity mask (Moore neighboorhood) \$\endgroup\$ – Luis Mendo May 11 '17 at 14:51
  • 3
    \$\begingroup\$ @LuisMendo That's awesome, learn something new on here every day, not always about code golfing \$\endgroup\$ – PunPun1000 May 11 '17 at 14:54
13
\$\begingroup\$

05AB1E, 8 bytes

4×ð«û3ô»

Try it online!

INPUT    # ['R']                 | Implicit Input: 'R'
---------#-----------------------+-------------------------------
4×       # ['RRRR']              | Repeat string 4 times.     
  ð      # ['RRRR',' ']          | Push space onto top of stack.
   «     # ['RRRR ']             | Concatenate last 2 items.
    û    # ['RRRR RRRR']         | Palindromize.
     3ô  # [['RRR','R R','RRR']] | Split into 3 pieces.
       » # ['RRR\nR R\nRRR']     | Join with newlines
---------#-----------------------+-------------------------------
OUTPUT   # RRR                   | Implicitly print the top
         # R R                   | of the stack on exit.
         # RRR                   |

Original idea using 30 as a binary number (unfinished, someone else try this in another lang):

05AB1E, 12 bytes

30bûTIð«‡3ô»

Try it online!

\$\endgroup\$
11
\$\begingroup\$

Python 3.6, 33 bytes

lambda c:f'{3*c}\n{c} {c}\n{3*c}'

Try it online!

\$\endgroup\$
  • \$\begingroup\$ No problem. It looks like it's actually 3.6.1 being run; if you try import sys and then sys.version in the repl, it returns 3.6.1 rather than 3.5.2. No idea why it says 3.5.2 at the top then, seems like they have made a mistake there! \$\endgroup\$ – numbermaniac May 13 '17 at 13:22
  • 2
    \$\begingroup\$ Oh, haha, a case of "don't always believe what you read" - thanks! \$\endgroup\$ – Jonathan Allan May 13 '17 at 13:23
9
\$\begingroup\$

RPL (Reverse Polish Lisp), 60 characters

→STR 1 4 START DUP NEXT " " + SWAP + 4 ROLLD + + SWAP 2 PICK

(Note that "→" is a single character on the HP48 and compatible calculators)

Would visually represent what you want by having three items on the stack:

3.: "###"
2.: "# #"
1.: "###"

If you insist to return it as one string, one has to add the newline characters as well and combine the strings, left as exercise to the next tester.

Input (can be anything, does not need to be a string) Entered code Result

Explanation:

  • →STR: Make the last object in the stack into a string. (So the input can be anything, e.g. a number.)
  • 1 4: Push the number 1 and 4 to the stack.
  • START [...] NEXT: Like a for loop but without access to the counter variable. Takes two numbers from the stack (here, we just have pushed 1 and 4) and executes the code [...] the corresponding times (here, four times).
  • DUP: Duplicate the last entry in the stack.
  • " ": Push the string (i.e. the string with one whitespace) to the stack.
  • +: Take two objects from the stack and return them added together, for strings: Concatenated.
  • 4: Push the number 4 to the stack.
  • ROLLD: Takes the last element (here: 4 that we just have pushed) from the stack and rolls the next element as far down the stack as the number we just took from the stack specifies.
  • SWAP: Swaps the two last stack elements.
  • 2: Push 2 to the stack.
  • PICK: Takes an element (here: The 2 we just pushed to the stack), interprets it as a number n, and copies the nth element from the stack.
\$\endgroup\$
7
\$\begingroup\$

JavaScript, 28 bytes

c=>c+c+c+`
${c} ${c}
`+c+c+c

Try it

f=
c=>c+c+c+`
${c} ${c}
`+c+c+c
o.innerText=f(i.value="#")
i.oninput=_=>o.innerText=f(i.value)
<input id=i maxlength=1><pre id=o>

\$\endgroup\$
  • \$\begingroup\$ I think you might be able to save a byte or two by storing the result of c+'\n'+c in a temporary. \$\endgroup\$ – Neil May 11 '17 at 14:48
  • \$\begingroup\$ Never mind, I miscounted, it's still 28 bytes. \$\endgroup\$ – Neil May 11 '17 at 14:48
  • \$\begingroup\$ @Neil: Yeah, there are a couple of options for assigning stuff to a variable, but they all come in at 28 bytes or more. \$\endgroup\$ – Shaggy May 11 '17 at 14:54
6
\$\begingroup\$

Jelly, 8 bytes

1 byte thanks to Erik the Outgolfer.

x4,`Ks3Y

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I was wondering how to do this... I had x4µ©;⁶;®œs3Y for 12 bytes because I couldn't figure out how to avoid having the repetition multiply my entire intermediate step but nice! \$\endgroup\$ – HyperNeutrino May 11 '17 at 14:50
  • 1
    \$\begingroup\$ You know, there's a builtin K for doing j⁶. Oh, and there's a quick, `, to convert a dyad to a monad by using the same argument on both sides. \$\endgroup\$ – Erik the Outgolfer May 11 '17 at 15:06
5
\$\begingroup\$

Java 7, 56 55 bytes

-1 Thanks to Leaky Nun for pointing out the space I missed

String a(char s){return"...\n. .\n...".replace('.',s);}

Simply replaces the periods with the given character, for input #:

...       ###
. .  =>   # #
...       ###

Try it online!

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

PHP, 32 Bytes

<?=strtr("000
0 0
000",0,$argn);

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Quite interestingly <?=$a=$argn,"$a$a\n$a $a\n$a$a$a"; (real line break instead of \n of course) has exactly the same byte count. \$\endgroup\$ – Christoph May 12 '17 at 6:26
  • \$\begingroup\$ @Christoph make it as your approach. i have not try this alternative way \$\endgroup\$ – Jörg Hülsermann May 12 '17 at 9:36
5
\$\begingroup\$

sed, 28 18 bytes

s:.:&&&\n& &\n&&&:

Try it online!

\$\endgroup\$
  • \$\begingroup\$ this new one doesnt work, the old one did edit: it does but you forgot the : in the anwser \$\endgroup\$ – Luc H May 11 '17 at 14:40
  • \$\begingroup\$ @Ayoungcoder Sorry, mis-pasted the final :. Fixed. \$\endgroup\$ – eush77 May 11 '17 at 14:41
  • \$\begingroup\$ the try it online should be [Try it online!]: tio.run/nexus/sed#@19spWelpqYWk6emACLU1Kz@/0/… "sed – TIO Nexus" \$\endgroup\$ – Luc H May 11 '17 at 14:42
  • \$\begingroup\$ @Ayoungcoder Of course, thanks. \$\endgroup\$ – eush77 May 11 '17 at 14:45
5
\$\begingroup\$

Brain-Flak, 76 70 + 1 = 71 bytes

Requires the -c flag

(((((((({})))<((([])[]{}<>)<>)>)<(<>({})({}){}()()<>)>)<([]()()())>)))

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You can save 6 bytes if you replace (()()()()()){} with ([])[]{}. \$\endgroup\$ – 0 ' May 11 '17 at 15:48
  • \$\begingroup\$ Some competition :) \$\endgroup\$ – DJMcMayhem May 11 '17 at 20:03
5
\$\begingroup\$

Pyth, 7 bytes

jc3.[9d

Try this online.

Explanation:

jc3.[9d Expects quoted input.
  3     3
     9  9
      d ' '
        Q (eval'd input) as implicit argument
   .[   Pad B on both sides with C until its length is a multiple of A
 c      Split B to chunks of length A, last chunk may be shorter
j       Join A on newlines
\$\endgroup\$
4
\$\begingroup\$

Brain-Flak, 61, 59 bytes

(((((((({})))<([][][]())>)<(([][][]()){})>)<([]()()())>)))

Try it online!

This is 58 bytes of code +1 byte for the -c flag which enables ASCII input and output.

Explanation:

(((
   (
    (
     (

      #Duplicate the input 3 times
      ((({})))

#Push 10 (newline)
<([][][]())>

     #Push the input again
     )

#Push 32 (space)
<(([][][]()){})>

    #Push the input again
    )

#Push 10 (newline)
<([]()()())>)

#Push input 3 times
)))
\$\endgroup\$
4
\$\begingroup\$

C (gcc), 49 47 bytes

Saved 2 bytes thanks to 2501!

j;f(i){for(j=12;j;)putchar(--j%4?j-6?i:32:10);}

Try it online! has a trailing newline

\$\endgroup\$
  • \$\begingroup\$ You can save two bytes by doing: for(j=11;j;)... \$\endgroup\$ – 2501 May 12 '17 at 9:38
3
\$\begingroup\$

Python 3, 34 bytes

lambda s:s*3+"\n"+s+" "+s+"\n"+s*3

Try it online!

\$\endgroup\$
  • \$\begingroup\$ -1 byte: lambda x:x*3+'\n%s '%x+x+'\n'+x*3 \$\endgroup\$ – Erik the Outgolfer Sep 16 '17 at 11:41
3
\$\begingroup\$

Octave, 36 bytes

x=repmat(input(0),3);x(5)=32;disp(x)

Try it online!

Explanation

This creates a 3x3 char matrix with the input char repeated, and sets its 5th entry in column-major order (i.e. its center) to 32 (ASCII for space).

\$\endgroup\$
3
\$\begingroup\$

Pyke, 5 bytes

dQA.X

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Ruby, 27 25 bytes

Saved 2 bytes thanks to Level River St

->x{[s=x*3,x+" "+x,s]*$/}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ when you are doing anwsers like this, please also include the footer as code because it does not work without \$\endgroup\$ – Luc H May 11 '17 at 19:51
  • \$\begingroup\$ @Ayoungcoder this is an anonymous function. you can assign it to a variable (f=...) then call it with f.call(...) \$\endgroup\$ – Cyoce May 11 '17 at 20:33
  • 1
    \$\begingroup\$ You can use a literal newline inside quotes instead of "\n" for a saving of 1 byte . Even better use $/ which is a special variable set to newline by default - saving 2 bytes. \$\endgroup\$ – Level River St May 11 '17 at 21:59
  • \$\begingroup\$ 1 byte less than the tr solution. nice work \$\endgroup\$ – Cyoce May 25 '17 at 5:14
3
\$\begingroup\$

Brainfuck, 40 bytes

+++++[->++<<++++++>],...>.<.<++.>.>.<...

Try it online! Requires an implementation that can access left of the starting position.

Also see: Graviton's brainfuck answer which takes a different approach (but is longer).


Explanation:

Brainfuck can do a lot of cool tricks with its limited instruction set. Unfortunately, this answer doesn't use any of them, because it's cheaper (in terms of bytes) to just hardcode everything.

+++++[->++<<++++++>]                         Sets the cells to |5*6|>0<|5*2|
,                   Takes input character into the middle cell | 30|>#<| 10|
...                                Print the top of the square | 30|>#<| 10| ###
>.                                   Print a newline character | 30| # |>10|    \n
<.                               Print another input character | 30|>#<| 10| #
<++.                  Add 30+2 for a space character and print |>32| # | 10|  _
>.                   And just print the 5 remaining characters | 32|>#<| 10|   #
>.                                                             | 32| # |>10|    \n
<...                                                           | 32|>#<| 10| ###

# = input character, _ = space (ASCII 32), \n = newline (ASCII 10)


Results in this beautiful box (for input '+'):

+++
+ +
+++
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 7 6 bytes

-1 byte thanks to carusocomputing.

ж¹ðJû

Explanation:

         # Implicit input                  # ['R']
 Ð       # Repeat string three times       # ['R', 'R', 'R']
  ¶      # Push newline character          # ['R', 'R', 'R', '\n']
   ¹     # Push first input                # ['R', 'R', 'R', '\n', 'R']
    ð    # Push space                      # ['R', 'R', 'R', '\n', 'R', ' ']
     J   # Join stack                      # ['RRR\nR ']
      û  # Palindromize ("abc" -> "abcba") # ['RRR\nR R\nRRR']
         # Implicit output                 # []

Uses the CP-1252 encoding. Try it online!

\$\endgroup\$
  • \$\begingroup\$ Oooo... Smart, I never think about how palindromize works on newlines. \$\endgroup\$ – Magic Octopus Urn May 31 '17 at 12:51
  • \$\begingroup\$ ж¹ðJû for 6 bytes. \$\endgroup\$ – Magic Octopus Urn May 31 '17 at 12:54
3
\$\begingroup\$

Pyth, 11 bytes

jc++K*z4dK3

Try it online!

Explanation:

jc++K*z4dK3    expects a single char as input

j              joins on new line
 c        3    chops array into 3 sized pieces
  +            joins +K*z4d and K
   +           joins K*z4 and d
    K          initialize variable K as *z4
     *z4       duplicate the input 4 times
        d      variable initialized to string " "
         K     calls variable K, in this case *z4
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Stephen Aug 13 '17 at 2:49
2
\$\begingroup\$

><>, 24 23 bytes

i:o:o:oao:o84*o:a0!.<o$

Try it online!

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

Swift3, 50 bytes

[1,2,3].map{$0==2 ? print(c+" "+c) : print(c+c+c)}

This uses the ternary operator to print different strings, depending on the row.

Try it online

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

V, 8 bytes

x3p2Ùlr 

Try it online!

\$\endgroup\$
  • \$\begingroup\$ V has a (undocumented?) <M-h>ollow command that lets you hollow out the inside of your box: Try it online! \$\endgroup\$ – nmjcman101 Sep 25 '17 at 20:13
2
\$\begingroup\$

C#,50 bytes

a=>Console.Write(a+a+a+"\n"+a+" "+a+"\n"+a+a+a);

Test Case:

var f = new Action<string>(
a=>Console.Write(a+a+a+"\n"+a+" "+a+"\n"+a+a+a);
);
f("#");
\$\endgroup\$
  • \$\begingroup\$ You need to fully qualify the Console i.e. System.Console.. \$\endgroup\$ – TheLethalCoder May 12 '17 at 10:56
2
\$\begingroup\$

Vim, 9 keystrokes

Assuming the input char is present in a buffer, vim makes this straightforward

x3pY2plr<space>

There is probably some magic vim commands of use here (there always seem to be some) so improvement suggestions are welcome. Only one keystroke behind V!

\$\endgroup\$
  • \$\begingroup\$ I'm pretty sure this is as short as it can get. Nice answer! \$\endgroup\$ – DJMcMayhem May 15 '17 at 18:36
2
\$\begingroup\$

Z80 or 8080 Assembly, 21 bytes machine code

Assume a memory mapped I/O device:

              Z80                  8080
3A xx xx    ld  a, (input)      lda  input       ; get input character
11 0A 20    ld  de, 200ah       lxi  d, 200ah   ; space & newline
21 yy yy    ld  hl, output      lxi  h, output  ; get output address
77          ld  (hl), a         mov  m, a       ; output character * 3
77          ld  (hl), a         mov  m, a
77          ld  (hl), a         mov  m, a
73          ld  (hl), e         mov  m, e       ; output newline
77          ld  (hl), a         mov  m, a       ; output character
72          ld  (hl), d         mov  m, d       ; output space
77          ld  (hl), a         mov  m, a       ; output character
73          ld  (hl), e         mov  m, e       ; output newline
77          ld  (hl), a         mov  m, a       ; output character * 3
77          ld  (hl), a         mov  m, a
77          ld  (hl), a         mov  m, a
76          halt                hlt             ; or C9 ret

No interpreter needed!

Hexdump:

0000: 3A 00 FF 11 0A 20 21 01 FF 77 77 77 73 77 72 77
0010: 73 77 77 77 76

where the input address is at FF00h and the output address is mapped at FF01h. The actual addresses will depend on the actual hardware. Of course this assumes the I/O is memory mapped. If it is I/O mapped, it would take several extra bytes because Z80 & 8080 I/O instructions are two bytes each. This also assumes the output device interprets 0Ah as a newline and doesn't require a CR (0Dh) which would add an extra 4 bytes to the program.

\$\endgroup\$
  • \$\begingroup\$ Welcome to Codegolf.stackexchange, while it seems that you have everything under control please do read the help center and the list of faqs. Good first post \$\endgroup\$ – Rohan Jhunjhunwala May 20 '17 at 1:41
  • \$\begingroup\$ Can you provide a hexdump of your code? \$\endgroup\$ – CalculatorFeline May 22 '17 at 16:30
  • \$\begingroup\$ The hex bytes are in the first column, but if you want a "pure" hexdump, I've added it. \$\endgroup\$ – Dan Howell May 23 '17 at 0:07
2
\$\begingroup\$

J-uby, 22 20 bytes

-2 bytes thanks to @Jordan

:tr&"...
. .
..."&?.

Explanation

String#tr is Ruby's character-wise replace method. The first & binds :tr to "...\n. .\n...", and the second partially applies '.' to it. Effectively, this is ->s{"...\n. .\n...".tr('.',s)}

\$\endgroup\$
  • \$\begingroup\$ Would :tr work as well as :gsub here? \$\endgroup\$ – Jordan May 25 '17 at 4:46
  • \$\begingroup\$ @Jordan yes, thanks! \$\endgroup\$ – Cyoce May 25 '17 at 5:02

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.