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.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 120052; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}

function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
return a.owner.display_name;
}

function process() {
var valid = [];

answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});

});

valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});

var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;

var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);

var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();

languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});

for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body { text-align: left !important}

#answer-list {
padding: 10px;
width: 290px;
float: left;
}

#language-list {
padding: 10px;
width: 290px;
float: left;
}

table thead {
font-weight: bold;
}

table td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">

</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">

</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>

• 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 May 11 '17 at 14:33
• 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. May 11 '17 at 14:56
• @Ayoungcoder It is a perfectly valid reason to downvote a challenge. May 11 '17 at 14:59
• @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.
– user62131
May 11 '17 at 15:33
• 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. May 13 '17 at 6:22

Charcoal, 5 3 bytes

Ｂ³Ｓ


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

Ｂ   Draw a box
³   3×3 (second dimension is implicit if omitted)
Ｓ   Using the input character

• I feel like this is cheating...>_> May 11 '17 at 14:50
• Then, of course, Ｂ³Ｓ to cheat the living crap outta this. May 11 '17 at 14:51
• Why would this be cheating? @carusocomputing and neil his anwser seems right to me May 11 '17 at 14:53
• @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. May 11 '17 at 14:54
• @carusocomputing Ah, the irony - the implicit square behaviour annoyed me in my answer to Visualize the Euclidean algorithm again.
– Neil
May 11 '17 at 14:56

Carrot, 11 bytes

###
# #
###


Try it online!

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

• The feeling when a program which looks completely invalid at first is actually perfectly valid. May 11 '17 at 16:01
• @EriktheOutgolfer ever heard of Perl? Aug 11 '17 at 4:45
• @EriktheOutgolfer ever heard of Brainfuck?
– user85052
Jan 4 '20 at 13:10

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

• How does this add the characters to the middle line? Could you explain the answer please? May 12 '17 at 13:26
• @Notts90 added an explanation c:
– Rod
May 12 '17 at 13:50
• thanks I didn't know .join could iterate a string. May 12 '17 at 13:55
• 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.) May 13 '17 at 13:49

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

• that was quick! didnt expect a 5 byte to come that fast. May 11 '17 at 14:26
• Code-golfing languages, you know... ¯\_(ツ)_/¯ May 11 '17 at 14:27
• Of course, because why wouldn't you have a predefined literal for [true true true; true false true; true true true] May 11 '17 at 14:48
• @PunPun1000 That's actually used a lot (together with convolution) as it's the standard 8-connectivity mask (Moore neighboorhood) May 11 '17 at 14:51
• @LuisMendo That's awesome, learn something new on here every day, not always about code golfing May 11 '17 at 14:54

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!

Python 3.6, 33 bytes

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


Try it online!

• 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! May 13 '17 at 13:22
• Oh, haha, a case of "don't always believe what you read" - thanks! May 13 '17 at 13:23

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.

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.

Jelly, 8 bytes

1 byte thanks to Erik the Outgolfer.

x4,Ks3Y


Try it online!

• 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! May 11 '17 at 14:50
• 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. May 11 '17 at 15:06

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>

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

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!

PHP, 32 Bytes

<?=strtr("000
0 0
000",0,$argn);  Try it online! • 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. May 12 '17 at 6:26
• @Christoph make it as your approach. i have not try this alternative way May 12 '17 at 9:36

sed, 28 18 bytes

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


Try it online!

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

Brain-Flak, 76 70 + 1 = 71 bytes

Requires the -c flag

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


Try it online!

• You can save 6 bytes if you replace (()()()()()){} with ([])[]{}. May 11 '17 at 15:48
• May 11 '17 at 20:03

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


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


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

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

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!

• Oooo... Smart, I never think about how palindromize works on newlines. May 31 '17 at 12:51
• Ð¶¹ðJû for 6 bytes. May 31 '17 at 12:54

Python 3, 34 bytes

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


Try it online!

• -1 byte: lambda x:x*3+'\n%s '%x+x+'\n'+x*3 Sep 16 '17 at 11:41

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

Pyke, 5 bytes

dQA.X


Try it online!

Ruby, 27 25 bytes

Saved 2 bytes thanks to Level River St

->x{[s=x*3,x+" "+x,s]*$/}  Try it online! • when you are doing anwsers like this, please also include the footer as code because it does not work without May 11 '17 at 19:51 • @Ayoungcoder this is an anonymous function. you can assign it to a variable (f=...) then call it with f.call(...) May 11 '17 at 20:33 • 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. May 11 '17 at 21:59
• 1 byte less than the tr solution. nice work May 25 '17 at 5:14

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 '+'):

+++
+ +
+++


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!

• I'm pretty sure this is as short as it can get. Nice answer! May 15 '17 at 18:36

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

• Welcome to PPCG! Aug 13 '17 at 2:49

StupidStackLanguage, 28 bytes

jfffavvflflqvvvviifblflflfff


Try it online!

Explanation

j # Get the input (x)
fff # first 3
avv # new line
fl # print new line
fl # first x
qvvvviifb # space
lf # second x
lf # new line
lfff # last 3 x's

• Welcome to the site :) Jan 30 '20 at 5:20

><>, 24 23 bytes

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


Try it online!

V, 8 bytes

x3p2Ùlr


Try it online!

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

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

• You need to fully qualify the Console i.e. System.Console.. May 12 '17 at 10:56

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.

• 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 May 20 '17 at 1:41
• Can you provide a hexdump of your code? May 22 '17 at 16:30
• The hex bytes are in the first column, but if you want a "pure" hexdump, I've added it. May 23 '17 at 0:07

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)}

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