31
\$\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\$
6
  • 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
    Commented May 11, 2017 at 14:33
  • 13
    \$\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
    Commented May 11, 2017 at 14:56
  • 34
    \$\begingroup\$ @Ayoungcoder It is a perfectly valid reason to downvote a challenge. \$\endgroup\$
    – Wheat Wizard
    Commented May 11, 2017 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
    Commented May 11, 2017 at 15:33
  • 6
    \$\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
    Commented May 13, 2017 at 6:22

93 Answers 93

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.

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

GolfScript, 13 bytes

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

Try it online!

Explanation

              # input #
4*            # ["####"]
  .           # ["####","####"]
   ' '        # ["####","####"," "]
      \       # ["####"," ","####"]
       ++     # ["#### ####"]
         3/   # [["###" "# #" "###"]]
           n* # [["###\n# #\n###"]]
\$\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
\$\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
\$\endgroup\$
1
\$\begingroup\$

J, 12 9 bytes

3 3$4j1#]

Try it online!

-3 thanks to FrownyFrog

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

1+, 40 38 bytes

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

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

\$\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!

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

K (ngn/k), 34 bytes

{`0:x,x,x,"\n",x," ",x,"\n",x,x,x}

Try it online!

The straightforward (although long) answer.

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

MATL, 8 bytes

4Y"0yv3e

Unlike my other MATL answer, this builds the output manually, without using any predefined literal.

Try it at MATL Online!

Explanation

Consider input '^' as an example.

      % Implicitly input one char.
4Y"   % Repeat 4 times. Gives a string.     STACK: '^^^^'
0     % Push 0. Char 0 is shown as space.   STACK: '^^^^', 0 
y     % Duplicate from below.               STACK: '^^^^', 0, '^^^^'
v     % Concatenate everything vertically.  STACK: ['^';'^';'^';'^';0'^';'^';'^';'^';'^']
3e    % Reshape into a 3-row char matrix.   STACK: ['^^^';'^ ^';'^^^']
      % Implicitly display.
\$\endgroup\$
1
\$\begingroup\$

Vyxal j, 40 bitsv2, 5 bytes

4*ð+∞²

Try it Online!

Bitstring:

0100101010111010101000100000000000001010

optimal encoding for a 6 byter

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

Retina, 21 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ It's shorter to match $ and insert $_ or $` (saving two bytes) \$\endgroup\$ Commented May 11, 2017 at 18:38
0
\$\begingroup\$

bash, 43 38 bytes

read -sN1 x
echo "$x$x$x
$x $x
$x$x$x"
\$\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!

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

VBScript, 72 bytes

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

VBScript sucks ;-)

\$\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!

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

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

Swift, 54 bytes

var s=readLine()!,a=s+s+s+"\n";print(a+s+" "+s+"\n"+a)
\$\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

\$\endgroup\$
8
  • 1
    \$\begingroup\$ This would use 52 bytes of program memory. \$\endgroup\$
    – Neil
    Commented Jun 4, 2017 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\$ Commented Jun 5, 2017 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
    Commented Jun 5, 2017 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\$ Commented Jun 5, 2017 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
    Commented Jun 5, 2017 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.

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

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

Ruby, 23+1 = 24 bytes

Uses the -n flag for +1 byte.

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

Try it online!

\$\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..."
\$\endgroup\$
1
  • \$\begingroup\$ You can shorten s:[] to [s]. \$\endgroup\$
    – Laikoni
    Commented May 20, 2017 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

\$\endgroup\$
1
  • \$\begingroup\$ Suggestion: Post you OCaml answer and Bash answers separately. \$\endgroup\$ Commented May 22, 2017 at 16:29
0
\$\begingroup\$

Python 2, 34 bytes

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

Try it online!

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

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

APL (Dyalog Extended), 15 bytes

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

Try it online!

Indexes into a binary matrix.

Requires ⎕IO←0(0-indexing)

\$\endgroup\$

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.