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

81 Answers 81

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

Python 3, 31 bytes

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

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
    \$\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 Jun 4 '17 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\$
  • \$\begingroup\$ You can save some bytes if you use r==1?" ":m directly in WriteLine, instead of assigning it to s. \$\endgroup\$ – raznagul May 12 '17 at 10:00
  • \$\begingroup\$ You need to fully qualify the Console \$\endgroup\$ – TheLethalCoder May 12 '17 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\$
  • \$\begingroup\$ @ConorO'Brien Thanks, for some reason I have a problem typing string the right way round... \$\endgroup\$ – TheLethalCoder May 12 '17 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\$
  • \$\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 May 19 '17 at 17:45
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\$
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\$
  • 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 May 19 '17 at 17:43
1
\$\begingroup\$

Japt, 11 9 bytes

³+R+U+S ê

Try it online


Explanation

    :Implicit input of string U
³   :Repeat input 3 times
+R  :Append newline
+U  :Append input
+S  :Append space
ê   :Duplicate string, excluding last character, reverse it and append it to original

Alternative, 9 bytes

I can't decide which version I prefer.

[U³RUS]¬ê

Try it online


Alternative, 10 bytes

I really liked this version, but sadly it came in at a byte too big.

NpU²RUS ¬ê

Try it online

\$\endgroup\$
  • \$\begingroup\$ Nice! p3 can be shortened to ³ \$\endgroup\$ – Oliver May 19 '17 at 14:37
  • \$\begingroup\$ Aha, hadn't spotted that. Thanks again, @obarakon. \$\endgroup\$ – Shaggy May 19 '17 at 14:39
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\$
  • \$\begingroup\$ oops, didnt allow trailing [] but never specified it, lucky ig guess :) \$\endgroup\$ – Luc H Sep 16 '17 at 6:37
  • \$\begingroup\$ Um why is -i on \$\endgroup\$ – CalculatorFeline Sep 25 '17 at 19:51
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\$
1
\$\begingroup\$

Dart, 30 bytes

f(s)=>'$s$s$s\n$s $s\n$s$s$s';

Try it online!

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

Keg, 11 bytes

???
? ? 
???

It really just replaces the ?s with the input!

Alterate 11 byter

¿3*:&
? ?
&
\$\endgroup\$
  • \$\begingroup\$ Neither program works on TIO \$\endgroup\$ – Jo King Dec 26 '19 at 9:12
  • \$\begingroup\$ Because Keg needs a pull on TIO \$\endgroup\$ – Lyxal Dec 26 '19 at 9:13
  • 1
    \$\begingroup\$ @JoKing Dennis is not very active this week. He didn't get the latest interpreter on TIO yet. \$\endgroup\$ – a'_' Dec 26 '19 at 9:13
  • \$\begingroup\$ @JoKing TIO is 19 commits behind the Keg repo \$\endgroup\$ – Lyxal Dec 26 '19 at 9:15
1
\$\begingroup\$

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

3IŽ9¦Λ

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ -1 byte by simply changing the Ƶ‘0« to Ž9¦ (see the How to compress large integers? section of this tip). \$\endgroup\$ – Kevin Cruijssen Jan 3 at 8:47
  • \$\begingroup\$ @KevinCruijssen Thanks, I was trying to use compressed integers but it wasn't getting the 0 at the start. \$\endgroup\$ – facepalm42 Jan 3 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\$ – Kevin Cruijssen Jan 4 at 11:52
1
\$\begingroup\$

naz, 46 bytes

1x1f0m9a1a1o0x1r2x1v3o1f1v1o0m4a8m1o1v1o1f1v3o

Strictly speaking, the above program outputs the exact byte stream required to make the square, though the top of the square will be misaligned given that the interpreter linked above always prepends output: to program output.

Explanation (with 0x commands removed)

1x1f0m9a1a1o     # Function 1
                 # Reset the register, add 10 and output (produces a newline)
1r2x1v           # Read the first byte of input and store it in variable 1
3o               # Output the byte 3 times
1f               # Call function 1
1v1o0m4a8m1o1v1o # Output variable 1, output 32 (space), then output variable 1
1f               # Call function 1
1v3o             # Output variable 1 3 times
\$\endgroup\$
1
\$\begingroup\$

W d, 13 11 9 bytes

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

ëu⑫⑺ƲȔ=Ƴ⑫

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

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

\$\endgroup\$
  • \$\begingroup\$ 13 bytes \$\endgroup\$ – a'_' Jan 23 at 4:20
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\$
  • \$\begingroup\$ It's shorter to match $ and insert $_ or $` (saving two bytes) \$\endgroup\$ – Martin Ender May 11 '17 at 18:38
0
\$\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\$
0
\$\begingroup\$

bash, 43 38 bytes

read -sN1 x
echo "$x$x$x
$x $x
$x$x$x"
\$\endgroup\$

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.