22
\$\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\$
  • 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\$ – Post Rock Garf Hunter 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

84 Answers 84

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

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

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

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

K (oK), 8 bytes

Solution:

3 3#5$4#

Try it online!

Example:

> 3 3#5$4#"@"
("@@@"
 "@ @"
 "@@@")

Explanation:

Evaluated right-to-left. Build 'AAAA', then 'AAAA ' and then shape into the 3x3 grid required.

3 3#5$4# / the solution
      4# / take 4 of whatever is to the right
    5$   / right pad with whitespace to length 5
3 3#     / shape into 3x3 grid

Bonus:

The solution is a polyglot for q/kdb+:

q)3 3#5$4#"*"
"***"
"* *"
"***"
\$\endgroup\$
  • \$\begingroup\$ cool way of doing it \$\endgroup\$ – Luc H Sep 26 '17 at 14:26
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\$

Acc!!, 58 bytes

N
Count i while 11-i {
Write _+i%4/3*(10-_)+i%6/5*(32-_)
}

Try it online!

How?

Let's lay out the desired output in a line, substituting _ for the newlines, and look at patterns and indices.

###_# #_###
01234567890

We need newlines at indices 3 and 7, a space at index 5, and the input character at all other indices. To put it a different way, for index i, we want newline when i%4 == 3, space when i%6 == 5*, and the input character otherwise.

So, after reading the input character into the accumulator with N, we run a Count loop from 0 up to but not including 11. Iff i%4 is 3, i%4/3 is 1, and we output _+(10-_) i.e. 10 i.e. newline. Iff i%6 is 5, i%6/5 is 1, and we output _+(32-_) i.e. 32 i.e. space. Otherwise, we output _ i.e. the accumulator value i.e. the input character. Fortunately, the two modulo cases are never true at the same time; this would happen at index 11, but we stop at index 10.


* The modulo operation would seem unnecessary here, but (as far as I can tell) it is the shortest way to test i == 5 in Acc!!, which doesn't have a comparison operator.

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

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

GolfScript, 13 bytes

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

Try it online!

Explanation

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

StupidStackLanguage 28 bytes

jfffavvflflqvvvviifblflflfff

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
New contributor
Lebster is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\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...

\$\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\$ – Post Rock Garf Hunter 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

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.