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

94 Answers 94

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\$
2
  • \$\begingroup\$ Would :tr work as well as :gsub here? \$\endgroup\$
    – Jordan
    Commented May 25, 2017 at 4:46
  • \$\begingroup\$ @Jordan yes, thanks! \$\endgroup\$
    – Cyoce
    Commented May 25, 2017 at 5:02
2
\$\begingroup\$

CJam, 11 10 bytes

r9*4St3/N*

Try it online!

Explanation:

r9*4St3/N* e# Expects single char (token) as input
r          e# Get input token (C)
 9*        e# Repeat C 9 times
   4St     e# Set the 5th char of C to be a space
      3/   e# Split into parts of length 3
        N* e# Join by newlines
\$\endgroup\$
2
\$\begingroup\$

Windows batch, 37 bytes

@echo %1%1%1
@echo %1 %1
@echo %1%1%1

Simply outputs the first command-line argument in a square form.

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

Emacs, 15 keystrokes

The current buffer must only contain the input character, and the cursor must be at the start of the line.

C-k C-y C-y C-y C-a C-k C-y RET C-y C-b BACKSPACE SPC C-e RET C-y
\$\endgroup\$
2
\$\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\$
2
\$\begingroup\$

05AB1E, 7 6 bytes using the canvas and compressed integers.

3IŽ9¦Λ

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ -1 byte by simply changing the Ƶ‘0« to Ž9¦ (see the How to compress large integers? section of this tip). \$\endgroup\$ Commented Jan 3, 2020 at 8:47
  • \$\begingroup\$ @KevinCruijssen Thanks, I was trying to use compressed integers but it wasn't getting the 0 at the start. \$\endgroup\$
    – mekb
    Commented Jan 3, 2020 at 20:34
  • 1
    \$\begingroup\$ You're right, 0s at the start (both with compressed integers and compressed integer lists) doesn't work. But since it has to be a square anyway, and your previous answer was appending the 0 at the end, it can be a single compressed integer 2460 to save a byte. :) \$\endgroup\$ Commented Jan 4, 2020 at 11:52
2
\$\begingroup\$

Python 3, 31 bytes

lambda s:3*s+f'\n{s} {s}\n'+3*s

Try it online!

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

MAWP, 29 bytes

|!;!;!;25W;!;84W;!;25W;!;!;;.

Try it!

-6 bytes from Dion's straightformard solution.

MAWP, 35 bytes

%|7[1A~!~]////25W//84W//25W////~[;]

Manually shifting the stack was more practical than trying to loop through it and make a box.

Try it!

\$\endgroup\$
4
  • \$\begingroup\$ Is this even golfed?? \$\endgroup\$ Commented Aug 15, 2020 at 8:13
  • \$\begingroup\$ ...Ok, I take it back. \$\endgroup\$ Commented Aug 15, 2020 at 8:56
  • \$\begingroup\$ Doesn't something so straightforward like this work..? \$\endgroup\$
    – Dion
    Commented Aug 18, 2020 at 18:51
  • \$\begingroup\$ What was I thinking when I made this?! \$\endgroup\$
    – Razetime
    Commented Sep 30, 2020 at 9:20
2
\$\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\$
2
\$\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\$
2
\$\begingroup\$

AWK, 24 bytes

sub(/./,"&&&\n& &\n&&&")

Attempt This Online! or try some more test cases.

This is one byte shorter than $0=$0$0$0RS$0FS$0RS$0$0$0.

This is basically regex substitution that takes one char and puts it into the box shape. sub without the 3rd argument takes and modifies $0 in-place. Since the substitution always succeeds, the sub call evaluates to true and the modified $0 is printed (the default action).

sub($0,...) doesn't work because some chars don't form a valid regex, such as [.

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

Japt -R, 11 9 8 bytes

³³h4S ò3

Try it

³³h4S ò3     :Implicit input of string
³³           :Repeat 9 times
  h4         :Replace the character at 0-based index 4 with
    S        :  Space
      ò3     :Partitions of length 3
             :Implicit output, joined with newlines
\$\endgroup\$
2
  • \$\begingroup\$ Nice! p3 can be shortened to ³ \$\endgroup\$
    – Oliver
    Commented May 19, 2017 at 14:37
  • \$\begingroup\$ Aha, hadn't spotted that. Thanks again, @obarakon. \$\endgroup\$
    – Shaggy
    Commented May 19, 2017 at 14:39
2
\$\begingroup\$

MathGolf, 7 bytes

·n\ ]yñ

Try it online.

Explanation:

·        # Quadruplicate the (implicit) input-character
 n       # Push a newline character "\n"
  \      # Swap the top two items
         # Push a space character " "
    ]y   # Wrap all values on the stack into a list, and join them to a string
      ñ  # Palidromize this string
         # (after which the result is output implicitly)
\$\endgroup\$
1
\$\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\$
1
\$\begingroup\$

Aceto, 19 bytes

nppk
pKLp
pppn
,kpp

Read a single character (,), then activate sticky mode (k). Print it three times, a newline and then the character again (pppnp).

Deactivate sticky mode (K), then load the empty string from quick storage (L), print it (p), activate sticky mode again (k), and print the rest (pnppp).

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

><>, 19 bytes

i:o:o:oao:$o" "|;o~

Try it online!

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

Retina, 18 bytes

:`$
$_$_
*2=`.



Half of this code looks like trailing empty lines, I like that :)

Try it online!

Explanation

There are three stages in this program, each of them prints a line of the output, in sequence.

:`$
$_$_

Add two more copies of the input at the end and print the resulting string.

*2=`.

There's a single space in the second line. This stage replaces the second character of the string with a space, prints the result, and then reverts the string to what it was before (thanks to the *)



The two final empty lines are a replacement stage with no effect. This is only needed because a final stage with no printing modifier implicitly prints the resulting string.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Save 1 byte by removing the third stage and putting the second stage into a group. The implicit print then moves from the stage to the group, allowing the stage's own dry run to be an additional output. (The ( needs to be at the start of the third line for this to work.) \$\endgroup\$
    – Neil
    Commented Jun 4, 2017 at 16:24
1
\$\begingroup\$

C#, 74 71 66 bytes

m=>{System.Console.WriteLine("{0}{0}{0}\n{0} {0}\n{0}{0}{0}",m);};

golfed 5 bytes thanks to an anon

\$\endgroup\$
2
  • \$\begingroup\$ You can save some bytes if you use r==1?" ":m directly in WriteLine, instead of assigning it to s. \$\endgroup\$
    – raznagul
    Commented May 12, 2017 at 10:00
  • \$\begingroup\$ You need to fully qualify the Console \$\endgroup\$ Commented May 12, 2017 at 10:56
1
\$\begingroup\$

C#, 30 bytes

s=>s+s+s+$"\n{s} {s}\n"+s+s+s;

Compiles to a Func<string, string>.

Using Replace for 32 bytes.

c=>@"###
# #
###".Replace('#',c);

Compiles to a Func<char, string>.

\$\endgroup\$
1
  • \$\begingroup\$ @ConorO'Brien Thanks, for some reason I have a problem typing string the right way round... \$\endgroup\$ Commented May 12, 2017 at 11:26
1
\$\begingroup\$

///, 27 bytes

/\\\#//\#\#\#
\#\ \#
\#\#\#

Try it online!

Since there is no other way to take input in ///, it is hard-coded.

/\\\#/INPUT HERE/\#\#\#
\#\ \#
\#\#\#

Version that takes input in Itflabtijtslwi (28 bytes):

GG\\\#GG\#\#\#
\#\ \#
\#\#\#

Try it online!

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

QBIC, 23 20 bytes

Brute-forcing this is shorter than fancy string-flips...

?;+A+A?A+@ `+A?A+A+A

Original answer:

A=;+A+A+@┘`+A?A+@ `+_fA

Explanation:

A=;     ; gets a cmd line parameter and assigns it to A$
        This overrides that value by
  +A+A    appending itself two times
  +@┘`    Then a literal newline
  +A      And another copy of the input char
?       PRINT
  A       The combined A$ ("###\n#")
  +@ `    a space
  +_fA    and then the flipped version of A$
\$\endgroup\$
1
\$\begingroup\$

Javascript (ES6), 32 bytes

i=>`###
# #
###`.replace(/#/g,i)
\$\endgroup\$
1
\$\begingroup\$

R, 43 40 bytes

cat(gsub("y",scan(,""),"yyy\ny y\nyyy"))

Saved 3 bytes thanks to Giuseppe.

Explanation: create a box using the character "y" and then substitute the input character.

\$\endgroup\$
2
  • \$\begingroup\$ You can drop 3 bytes by reading x from stdin instead of making it a function: cat(gsub("y",scan(,""),"yyy\ny y\nyyy")) \$\endgroup\$
    – Giuseppe
    Commented May 19, 2017 at 17:45
  • \$\begingroup\$ using 1 in place of "y" saves 2 more bytes. \$\endgroup\$
    – Giuseppe
    Commented Jan 30, 2020 at 19:16
1
\$\begingroup\$

Cubix, 26 bytes

./v.o;@?/i:::Ns:Ss:Nu/:::s

This is the first piece of Cubix code I've ever written...I was originally going to try to answer the Try to make a cube challenge, but I figured I'd answer the original (easier) question first. Cubix is pretty cool!

Try it online! and also Watch the interpeter!

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

R, 44 bytes

cat(y<-rep(scan(,''),4),' ',y,sep='',fill=3)

Test and output:

> cat(y<-rep(scan(,''),4),' ',y,sep='',fill=3)
1: #
2: 
Read 1 item
###
# #
###
> 
\$\endgroup\$
1
  • 2
    \$\begingroup\$ You can drop a few bytes by returning an anonymous function, but you can do even better by reading from stdin: cat(y=rep(scan(,''),4),' ',y,sep='',fill=3) is 43 bytes. \$\endgroup\$
    – Giuseppe
    Commented May 19, 2017 at 17:43
1
\$\begingroup\$

brainfuck, 48 bytes

Great simple challenge.

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

Try it online!

Explanation

,...              : take input, print it 3 times
>++++++++++.      : print ASCII with index 10 (new line)
<.>               : print input.
+[->+>+++<<]>>-.  : add 1 to 10, triple it, subtract one and print it (space)
<<<.>>-.<<...     : print input, newline, and input 3 times
\$\endgroup\$
1
\$\begingroup\$

Perl 5, 23 + 1 (-p) = 24 bytes

The brute force way seems to be the shortest.

$_.="$_$_
$_ $_
$_$_$_"

Try it online!

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

Syms, 21 bytes

{}<[[[++~[{& &}~[>~>>

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ oops, didnt allow trailing [] but never specified it, lucky ig guess :) \$\endgroup\$
    – Luc H
    Commented Sep 16, 2017 at 6:37
  • \$\begingroup\$ Um why is -i on \$\endgroup\$ Commented Sep 25, 2017 at 19:51
1
\$\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\$
1
  • \$\begingroup\$ cool way of doing it \$\endgroup\$
    – Luc H
    Commented Sep 26, 2017 at 14:26
1
\$\begingroup\$

Pepe, 54 bytes

REEeREEEeeReeerREeeeeEeEeReeereeeEeeeeeReeeREEeeReReee

Try it

Explanation:

REEe        # Input as str
REEEee      # Duplicate it
Reee        # Output whole stack
rREeeeeEeEe # Insert linefeed (10) to the stack
Reee        # Output whole stack
reeeEeeeee  # Print space (' ')
Reee        # Output whole stack
REEee       # Go to next position
ReReee      # Pop it (space) and output the whole stack
\$\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.