26
\$\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.

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>

\$\endgroup\$
  • 3
    \$\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
  • 33
    \$\begingroup\$ @Ayoungcoder It is a perfectly valid reason to downvote a challenge. \$\endgroup\$ – Wheat Wizard 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

89 Answers 89

1 2
3
1
\$\begingroup\$

GolfScript, 15 bytes

...n\." "\.n\..

Explanation

At the beginning of the program, the input is put onto the stack. Each . copies the top of stack. Each n pushes a newline onto the stack. " " pushes a space. \ swaps the top two elements. At the end of the program, the stack is output to the standard output.

Try it Online

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 13 bytes \$\endgroup\$ – user85052 Jan 23 at 4:20
1
\$\begingroup\$

TI-BASIC, 14 + 6 = 20 bytes

This submission uses two programs, the main one and a helper program called prgmΘ.

prgmΘ:Disp Ans+" "+Ans:prgmΘ         ;main program

Disp Ans+Ans+Ans                     ;helper program "prgmΘ"

Input is a string stored in Ans.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

GolfScript, 13 bytes

4*.' '\++3/n*

Try it online!

Explanation

              # input #
4*            # ["####"]
  .           # ["####","####"]
   ' '        # ["####","####"," "]
      \       # ["####"," ","####"]
       ++     # ["#### ####"]
         3/   # [["###" "# #" "###"]]
           n* # [["###\n# #\n###"]]
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Husk, 6 bytes

Husk is way easier to use than Pyth.

C3w½*8

Try it online!

Explanation

    *8 Repeat the input 8 times. "!" -> "!!!!!!!!"
   ½   Halve the input. "!!!!!!!!" -> ["!!!!","!!!!"]
  w    Join with spaces. ["!!!!","!!!!"] -> "!!!! !!!!"
C3     Split into chunks of 3. ["!!!","! !","!!!"]

Husk automatically outputs lists joined with newlines
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

W d n, 8 bytes

º±▀σ\g┘╒

Uncompressed:

4*:' S++3,

Explanation:

4*         Repeat input 4 times
  :' S++   Put space in middle, append input * 4
        3, Chop into 3 equal pieces
Flag: n Join with newlines

W d, 13 11 9 bytes

Here's a version without chopping or similar built-ins.

↨i`♣T'@└µ

Explanation

Uncompressed is:

' a++bab++E
          E % Foreach in the string:
' a++       % (implicit) input, the space, and input
     bab++  % Output the string created by the input,
            % the current item, and the input
            % With a newline
            % The None isn't outputted
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

J, 12 9 bytes

3 3$4j1#]

Try it online!

-3 thanks to FrownyFrog

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 3 3$4j1#] for 9 \$\endgroup\$ – FrownyFrog Feb 6 at 3:40
  • \$\begingroup\$ That is quite nice. I had long forgotten about that complex trick, if I ever knew it. \$\endgroup\$ – Jonah Feb 6 at 4:32
1
\$\begingroup\$

1+, 40 38 bytes

,";";";(|11+""*")++";^";()**;";^;";";;

Longer than I thought. Ungolfed, but it's a start.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Poetic, 208 bytes

BOX,OR SQUARE
i was creating a side,i built a box
i looked,it was four-sided
i am somewhat weirdly earnest,however,about n*n squares having a"no-holes-in-a-drawing"shape
i am trying to produce regular squares

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Braingolf, 34 20 bytes

...#
<.># <.>#
<..&@

Little disappointed that this isn't easily golfed. At least it's shorter than JavaScript

Explanation:

For input #

                   | [35]
...                | [35,35,35,35]
   #<newline>      | [35,35,35,35,10]
<.>                | [35,35,35,35,10,35]
   #<space>        | [35,35,35,35,10,35,32]
     <.>           | [35,35,35,35,10,35,32,35]
        #<newline> | [35,35,35,35,10,35,32,35,10]
<..                | [35,35,35,10,35,32,35,10,35,35,35]
   &@              | Print entire stack

35 = # ASCII value
10 = <newline> ASCII value
32 = <space> ASCII value

Output:
###
# #
###
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Retina, 21 bytes

.
$&$&$&¶$& $&¶$&$&$&

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It's shorter to match $ and insert $_ or $` (saving two bytes) \$\endgroup\$ – Martin Ender May 11 '17 at 18:38
0
\$\begingroup\$

bash, 43 38 bytes

read -sN1 x
echo "$x$x$x
$x $x
$x$x$x"
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Scala, 23 bytes

a=>a*3+s"\n$a $a\n"+a*3

Accepts and returns a String. The s before a string literal allows you to use $-prefixed variables in it, or even ${expressions}. * repeats a String, like in Python.

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

VBScript, 72 bytes

n=chr(10):msgbox replace("###"&n&"# #"&n&"###","#",wscript.arguments(0))

VBScript sucks ;-)

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Foo, 40 bytes

&<character as ascii value>&3(-1<$c>)$c13<$c$c32$c$c13>&3(-1<$c>)

As Foo cannot take input, you should replace <character as ascii value> with the ASCII value of the character.

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Befunge, 26 bytes

~:::25*\:84*\:25*\::>:#,_@

Try it online!

Explanation

~::          Take input and put bottom row in stack (: is duplicate)
:25*\:84*\   Create second row (25* is 10 or newline, 84* is 32 or space)
:25*\::      Create top row
>:#,_@       Print out stack until the stack is empty

the \ after the numbers is to switch the stack around since you need the input on 
top of the stack to duplicate it
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Common Lisp, SBCL, 50 bytes

(format t"~@?
~a ~:*~a
~@*~@?""~3@{~a~:*~}"(read))

Explanation

format              ;printing function
~@?                 ;execute format string given as argument
~a ~:*~a            ;print current argument (will be result of (read))
                    ;then print space, go back one argument (to again use 
                    ;result of (read) and print it  
~@*~@?              ;go back to first argument, then execute format string 
                    ;given as this argument
"~3@{~a~:*~}"       ;loop three times printing argument number 2 
                    ;~:* makes it keep going back to argument number 2
(read)              ;take input

Ideas for improvement are welcomed.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Swift, 54 bytes

var s=readLine()!,a=s+s+s+"\n";print(a+s+" "+s+"\n"+a)
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Sinclair ZX80/ZX81 (without sanity check), ~55 Bytes (listing)

 1 INPUT A$
 2 PRINT A$;A$;A$
 3 PRINT A$;" ";A$
 4 PRINT A$;A$;A$

With sanity check (ZX80 with 8K ROM or ZX81)

 1 INPUT A$
 2 IF NOT LEN A$ OR LEN A$>1 THEN GOTO 1
 3 PRINT A$;A$;A$
 4 PRINT A$;" ";A$
 5 PRINT A$;A$;A$

Line two of the latter version makes sure that there is a single character entered. So in the first example, it is possible to enter nothing and simply press NEW LINE.

The BASIC listing result with entry of asterisk

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ This would use 52 bytes of program memory. \$\endgroup\$ – Neil Jun 4 '17 at 16:29
  • \$\begingroup\$ So my approximation is broadly correct? I keep forgetting to POKE the memory to see how much actual RAMs my ZX80/81 programs take up; it also depends on the ROM used in the ZX80. If it's the 'old ROM' then each numeric variable is a 16-bit signed integer only, taking two bytes, whereas with the 8K ROM upgrade that becomes a floating point number of 5 bytes in memories total. \$\endgroup\$ – Shaun Bebbers Jun 5 '17 at 8:36
  • 1
    \$\begingroup\$ Ah, well fortunately your program contains no numbers (at least, not the short version, which is what I counted). Also, I hope you PEEK to find out the actual usage, which would be PRINT PEEK 16396 + 256 * PEEK 16397 - 16509. \$\endgroup\$ – Neil Jun 5 '17 at 8:44
  • \$\begingroup\$ Thanks for this. I was making a general point about all of my ZX80/ZX81 entries rather than something specific about this listing \$\endgroup\$ – Shaun Bebbers Jun 5 '17 at 8:49
  • \$\begingroup\$ I'm just amazed that you have a ZX80 with the 8K ROM upgrade. (I'm just marginally too young for that, having started with the ZX81.) \$\endgroup\$ – Neil Jun 5 '17 at 9:11
0
\$\begingroup\$

PowerShell, 26 Bytes

param($c)$c*3;"$c $c";$c*3

takes a char/length 1 string - then prints it 3 times, it twice with a separating space, and it 3 times again.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

braingasm, 18 bytes

,...10..32..10....

Yeah... read a byte, print it three times, then print a newline (10), then the byte again, then a space (32), that byte again, another newline and that byte three more times...

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Ruby, 23+1 = 24 bytes

Uses the -n flag for +1 byte.

puts$_*3,$_+' '+$_,$_*3

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Haskell, 45 44 bytes

-1 byte thanks to Laikoni

Naive approach

f s=putStrLn$s:s:s:'\n':s:' ':s:'\n':s:s:[s]

For some reason

f s=putStr$s:s:s:'\n':s:' ':s:'\n':s:s:[s]

won't output the last line on repl.it, but if it's still valid it shaves off 2 bits for a total of 42

And

f s=print$s:s:s:'\n':s:' ':s:'\n':s:s:[s]

will print the answer as "sss\ns s\nsss" instead of properly linebreaking. If that's valid it shaves off 3 bits for a total of 41

There is a solution with replace that's 42 bits long ... but that's without counting the bytes needed to import the necessary module. For reference:

import Data.String.Utils
f s=putStrLn$replace "." s "...\n. .\n..."
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can shorten s:[] to [s]. \$\endgroup\$ – Laikoni May 20 '17 at 12:37
0
\$\begingroup\$

OCaml, 53 bytes

let f c=String.map(function '#'->c|c->c)"###
# #
###"

It's pretty bad. OCaml does not even have a replace function

Bash, 26 bytes

echo "$1$1$1
$1 $1
$1$1$1"

5 bytes less boring

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Suggestion: Post you OCaml answer and Bash answers separately. \$\endgroup\$ – CalculatorFeline May 22 '17 at 16:29
0
\$\begingroup\$

Python 2, 34 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Excel VBA, 27 Bytes

Anonymous VBE immediate window function that takes input from cell [A1] on the Application.ActiveSheet object and outputs a 'square' to the VBE immediate window.

a=[A1]:?a;a;a:?a" "a:?a;a;a
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

UGL, 23 Bytes

j"\n"++l*I3l++i" "il*i3

try it online (write the code to stdin. you can also use the link at the top of the answer to try online, that accepts ctrl+v)

Equivalent Python code:

cur_inp = ""
def inp():
    global cur_inp
    cur_inp = input()
    return cur_inp
"\n".join([inp*3]+[cur_inp+" "+cur_inp]+[cur_inp*3])

Using Python's string multiplication.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Burlesque, 20 bytes

3.*3.*{1 1}' D!)\[un

Try it online!

3.*       # Make a list of 3 instances     {A A A}
3.*       # Again                          {{A A A} {A A A} {A A A}}
{1 1}' D! # Set value at 1,1 to a space    {{A A A} {A   A} {A A A}}
)\[       # Concatenate each internal list {"AAA" "A A" "AAA"}
un        # Join array with newlines

Burlesque, 23 bytes

495b2"1"x/r~'0' r~3coun

Try it online!

Just for a bit of variety

495b2   # Read the number 495 as binary (111101111)
"1"x/r~ # Replace 1s with input char
'0' r~  # Replace 0 with space
3co     # Chunks of 3
un      # Separate by newlines
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

APL (Dyalog Extended), 15 bytes

(' ',⍞)[⊤7 5 7]

Try it online!

Indexes into a binary matrix.

Requires ⎕IO←0(0-indexing)

| improve this answer | |
\$\endgroup\$
-1
\$\begingroup\$

Javascript (in-console), 42 bytes

for(i=3;i;i--)console.log(i%2?'iii':'i i')

Alternatively, this abomination:

i=3;while(i--)console.log(i%2?'i i':'iii')

The previous JavaScript answer was really cool, but you still need extra JavaScript to print out the square into the console or into an HTML element. I'm going for the shortest code including printing. If you put this code in-between two script tags and save it as an HTML page (so you aren't putting the code directly into the console) it's still only 59 bytes, but you can just run it from the developer console for the 42 bytes.

Explanation

for loop

i has to remain true for the for loop to keep running. When it hits 0 it is false and so stops. Counting down instead of up lets us save 2 characters over i=1;i=3;i++.

The code also has no spaces or semicolons- bad, I know. But with just one line, it still works!

The ternary operator reads "If i divided by 2 equals 0 (so if i is 2), print iii; otherwise, print i i." This means only the second line will print i i.

while loop

The while loop was a test that didn't get any fewer bytes, but was interesting. i is just defined outside of the loop. I didn't know that you could iterate inside of the while statement; it still goes until i becomes 0 from what I can tell. I don't know if this works cross-browser, but it worked in Chrome. I can't help but think there's a way to shorten the while version more, but I haven't figured it out yet...

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ First of all, welcome to the site! This looks like a very thorough first answer. Second, excuse me for being JavaScript illiterate but how does this program take input? It appears to me, again I'm completely illiterate in Javascript, this always print a square of is or perhaps a square made of the numbers 2, 1, and 0. \$\endgroup\$ – Wheat Wizard Sep 18 '17 at 3:47
  • \$\begingroup\$ I think the program is supposed to take a character of input and then create a square consisting of that character. \$\endgroup\$ – Esolanging Fruit Sep 18 '17 at 4:53
  • \$\begingroup\$ Also, you can collapse the the --i and the i into the middle section of the for loop to save a byte (but you'll have to swap the branches on the ? statement). \$\endgroup\$ – Esolanging Fruit Sep 18 '17 at 4:54
  • \$\begingroup\$ @FunkyComputerMan Thank you! In JavaScript, surrounding values with single quotes makes them into strings. The string could have been anything besides 'i', I just chose 'i' for the heck of it (and I was brainstorming if I could somehow print the character as well as the variable name and use some sort of hack there). \$\endgroup\$ – Josh Powlison Sep 18 '17 at 21:05
  • \$\begingroup\$ @Challenger5 Comment 1: Looking at the description again, you may be right. "Given one non-whitespace printable character, make a 3x3 square representation of that input." But that could imply that input needs to be 1 variable, and I'm not sure that most of these answers follow that (that said, I'm not fluent in a lot of these languages, so I could just be unable to read them right). I'm not 100% sure, so I'll keep my answer here. Comment 2: Could you show me what the code would be? The shorthand you're referring to sounds familiar, but I'm struggling to find it online. \$\endgroup\$ – Josh Powlison Sep 18 '17 at 21:12
1 2
3

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.