28
\$\begingroup\$

Your task: given a number n, generate a '+' sign that is n characters away from its center. If this is confusing, check out the test cases.

Standard methods of input: output must be a string or printed. Standard loopholes apply.

Input: 1
Output: +           ] 1 away from center `+`.

Input: 2
Output:  +          ] 2 away from center `+`.
        +++         ] 1 away from center `+`.  
         +

Input: 3
Output:   +         ] 3 away from center `+`.
          +
        +++++
          +
          +

This is , so shortest code wins!

\$\endgroup\$
  • \$\begingroup\$ I assume trailing spaces on each line are allowed so that the result is square, right? \$\endgroup\$ – Luis Mendo Apr 11 '17 at 15:29
  • \$\begingroup\$ @LuisMendo Yes, that is fine. \$\endgroup\$ – Comrade SparklePony Apr 11 '17 at 15:31
  • \$\begingroup\$ Related. \$\endgroup\$ – Neil Apr 11 '17 at 19:29
  • 3
    \$\begingroup\$ "generate a '+' sign that is n characters away from its center" -- I don't understand this part. What center are you referring to? How can something be eccentric to itself? Please clarify. \$\endgroup\$ – Wossname Apr 13 '17 at 6:43
  • 6
    \$\begingroup\$ It would have been a lot less confusing if the centre were 0 away from itself. \$\endgroup\$ – Stop Harming Monica Apr 13 '17 at 13:45

42 Answers 42

45
\$\begingroup\$

Charcoal, 5 bytes

P+×+N

Try it online!

\$\endgroup\$
  • 22
    \$\begingroup\$ What even is this language? \$\endgroup\$ – DJMcMayhem Apr 11 '17 at 19:40
  • \$\begingroup\$ @DJMcMayhem Basically you can do turtle graphics ASCII art with it. It has a lot of handy builtins for rendering different kind of ASCII shapes (like P+ = cross). \$\endgroup\$ – fergusq Apr 11 '17 at 20:12
  • \$\begingroup\$ Are those not multibyte characters? \$\endgroup\$ – Petah Apr 12 '17 at 2:36
  • 3
    \$\begingroup\$ @Petah Charcoal uses a custom codepage. \$\endgroup\$ – ASCII-only Apr 12 '17 at 4:45
  • \$\begingroup\$ @fergusq You might be mixing Charcoal up with Turtlèd :P, Charcoal isn't really a turtle graphics language \$\endgroup\$ – ASCII-only Apr 12 '17 at 4:48
25
\$\begingroup\$

Python 2, 53 bytes

n=2*input()-1;C='+'.center
for c in C(n):print C(n,c)

Try it online!

\$\endgroup\$
12
\$\begingroup\$

JavaScript (ES6), 67 65 63 60 59 bytes

x=>(v=(` `[r=`repeat`](--x)+`+
`)[r](x))+`+`[r](x*2)+`+
`+v;
  • 2 bytes saved by replacing two occurrences of x-1, the first with --x and the second with x.
  • 2 bytes saved thanks to Kritixi Lithos, replacing "\n" with `[newline]`.
  • 3 bytes saved thanks to user2428118, finally helping me to figure out a way to alias the repeat in a way that reduced the size. (With honourable mention to Marie for her efforts, too)
  • 1 byte saved indirectly thanks to Herman.

Try It

f=
x=>(v=(` `[r=`repeat`](--x)+`+
`)[r](x))+`+`[r](x*2)+`+
`+v;
oninput=_=>o.innerText=f(+i.value)
o.innerText=f(i.value=3)
<input id=i min=1 type=number><pre id=o>

\$\endgroup\$
  • 1
    \$\begingroup\$ I'm not entirely sure, but I think you can replace the "\n" with two backticks and a literal newline between them \$\endgroup\$ – Kritixi Lithos Apr 11 '17 at 15:54
  • \$\begingroup\$ Thanks, @KritixiLithos; don't know why I didn't think of that sooner myself. \$\endgroup\$ – Shaggy Apr 11 '17 at 16:04
  • 1
    \$\begingroup\$ It looks like you could probably save a byte by aliasing repeat, e.g. a='repeat',v=..... and ` `[a] \$\endgroup\$ – Marie Apr 11 '17 at 17:12
  • \$\begingroup\$ Thanks, @Marie; I had tried aliasing repeat() but my first few attempts came out 2 or 3 bytes bigger so I abandoned it! I'll have another look at it when I get back in front of a computer. \$\endgroup\$ – Shaggy Apr 11 '17 at 17:22
  • 2
    \$\begingroup\$ x=>(v=(` `[r='repeat'](--x)+`+<newline>`)[r](x))+`+`[r](x*2+1)+`<newline>`+v \$\endgroup\$ – user2428118 Apr 12 '17 at 15:40
9
\$\begingroup\$

MATL, 11 bytes

tZv=&+g43*c

Try it online!

Explanation with example

Consider n = 3.

t     % Implicitly input n. Duplicate
      % STACK: 3, 3
Zv    % Symmetric range
      % STACK: 3, [1 2 3 2 1]
=     % Equal, element-wise
      % STACK: [0 0 1 0 0]
&+    % All pair-wise additions. Gives a 2D array
      % STACK: [0 0 1 0 0;
                0 0 1 0 0;
                1 1 2 1 1;
                0 0 1 0 0;
                0 0 1 0 0]
g     % Logical: convert non-zero to one
      % STACK: [0 0 1 0 0;
                0 0 1 0 0;
                1 1 1 1 1;
                0 0 1 0 0;
                0 0 1 0 0]
43*   % Multiply by 43 (ASCII for '+'), element-wise
      % STACK: [ 0  0 43  0  0;
                 0  0 43  0  0;
                43 43 43 43 43;
                 0  0 43  0  0;
                 0  0 43  0  0]
c     % Convert to char. Char 0 is displayed as space. Implicitly display.
      % STACK: ['  +  ';
                '  +  ';
                '+++++';
                '  +  ';
                '  +  ']
\$\endgroup\$
8
\$\begingroup\$

Charcoal, 16 13 bytes

Nα×+α←↑×+α‖O↘

Try it online!

Uses a different approach from the other Charcoal answer.

Explanation

Nα                       # Take input and store it in variable α
×+α                       # α times write a +
←                         # Go left
↑×+α                      # α times write a + upwards

Now the top left corner is complete, it will look something like this:

  +
  +
+++

‖O↘                      # Reflect-overlap it in a SE direction

The last step is the key to this program, it uses the top-left part of the plus to generate the rest of the plus by reflecting it in the southeast direction (rightwards and downwards).

\$\endgroup\$
  • \$\begingroup\$ Does Charcoal have its own code page? Many of those characters are multiple bytes in UTF-8. \$\endgroup\$ – TRiG Apr 12 '17 at 10:18
  • \$\begingroup\$ @TRiG Yes, it does! \$\endgroup\$ – Kritixi Lithos Apr 12 '17 at 10:25
8
\$\begingroup\$

Shakespeare Programming Language, 749 743 bytes

N.Puck,.Page,.Ford,.Ajax,.Act I:.Scene I:.[Enter Puck and Ford]Puck:Listen to thy heart!Ford:You is the difference between a cat and I.Scene V:.[Exeunt][Enter Page and Ajax]Ajax:You is the difference between a cat and Ford.Scene X:.Page:You is the product of Puck and I.Is you as big as zero?If so,you is the sum of the sum of the sum of a big big big big big cat and a big big big cat and a big cat and a cat.If not,you big big big big big cat.Speak thy mind!Ajax:You is the sum of you and a cat.Is you as big as Ford?If not,let us return to Scene X.Page:You is the sum of a big big big cat and a big cat.Speak thy mind![Exit Page][Enter Puck]Ajax:You is the sum of you and a cat.Is you as big as Ford?If not,let us return to Scene V.[Exeunt]

Try it online!

Edit: made the answer compatible with the official SPL implementation - I couldn't get it to work before.

Golfed 6 bytes because scene numbers don't have to be consecutive.

Explaination:

SPL is an esolang designed to look like Shakespeare plays. Positive nouns have the value of 1 (here cat is used) and negative nouns have the value of -1 (none were used but pig is one of them). Adjectives modify a constant by multiplying it by 2.

N.

Everything until the first dot is the title and doesn't matter.

Puck,.                           row counter
Page,.                           column counter
Ford,.                           input
Ajax,.                           temp

The characters are integer variables, each of them also has a stack but I did not need to use that feature.

Act I:.
Scene I:.

Acts and scenes are used as goto labels

[Enter Puck and Ford]

It's only useful if exactly two characters are on the stage at the same time.

Puck:Listen to thy heart!

Reads a number and makes Ford remember it.

Ford:You is the difference between a cat and I.

As you can see Engrish is valid in SPL. This makes Puck's value "the different between a cat and I". But what does it mean? cat is a positive noun, so it's Puck = 1 - Ford.

Scene II:.
[Exeunt]

Exeunt is just a plural of "exit", and without arguments means that everyone on the stage exits.

[Enter Page and Ajax]
Ajax:You is the difference between a cat and Ford.

It's also Page = 1 - Ford but it's spoken by a different actor so I would be wrong. Since it's a loop, I can't just copy the value of Puck.

Scene III:.
Page:You is the product of Puck and I.

Pretty straightforward by now. Ajax = Puck * Page.

Is you as big as zero?

"as [adj] as" is the == operator.

If so,you is the sum of the sum of the sum of a big big big big big cat and a big big big cat and a big cat and a cat.

If Ajax == 0... "cat" is 1, "big cat" is 2, "big big cat" is 4 and so on. After substituting the simple constants we get "the sum of the sum of the sum of 32 and 8 and 2 and 1" -> "the sum of the sum of 40 and 2 and 1" -> "the sum of 42 and 1" -> "43", which is the ASCII for +.

If not,you fat fat fat fat fat cat.

else it's just "fat fat fat fat fat cat", so Ajax gets the value of 32, the ASCII for a space.

Speak thy mind!

This is the command for outputting a character.

Ajax:
You sum you and cat.Is you as big as Ford?If not,let us return to Scene III.

This is a loop construct. "You sum you and cat" increments Page, and if(Page != Ford) goto Scene III. The rest of the program uses the same components, so here is a more readable pseudocode version:

Scene1:
    input = [input number];
    row = 0 - input + 1;
Scene2:
    col = 0 - input + 1;
Scene3:
    temp = row * col;
    if(temp == 0){
        temp = '+';
    }else{
        temp = ' ';
    }

    putchar(temp);
    Page = Page + 1;
    if(Page != Ford) goto Scene3;
    Ajax = 10;
    putchar(Ajax);
    Puck = Puck + 1;
    if(Puck != Ford) goto Scene2;
\$\endgroup\$
  • \$\begingroup\$ "If not,let us return to Scene III." -1; breaks fourth wall :P \$\endgroup\$ – Jakob Aug 14 '17 at 20:14
7
\$\begingroup\$

Jelly, 11 bytes

ṬŒB»þ`ị⁾+ Y

Try it online!

\$\endgroup\$
  • 4
    \$\begingroup\$ fingers crossed :-P \$\endgroup\$ – Luis Mendo Apr 11 '17 at 15:48
6
\$\begingroup\$

Mathematica, 39 bytes

Print@@@(CrossMatrix[#-1]"+"/. 0->" ")&

CrossMatrix is a built-in that generates a matrix of the required shape with 1s instead of +s and 0s instead of spaces. If we multiply that matrix by "+", that replaces the 1s with +s while leaving the 0s unchanged (obviously... 0*x = 0 and 1*x = x, right?). Then we replace the zeros manually with spaces using /. 0->" ". Finally, we print each line of the matrix with Print@@@(...).

\$\endgroup\$
  • 1
    \$\begingroup\$ Didn't know Print could be used like that. \$\endgroup\$ – ngenisis Apr 12 '17 at 17:34
6
\$\begingroup\$

C, 69 bytes

Not very interesting... Loops over the square, printing out the appropriate character.

r,c;f(n){for(r=-n;++r<n;puts(""))for(c=-n;++c<n;putchar(r*c?32:43));}
\$\endgroup\$
6
\$\begingroup\$

Ruby, 41 40 bytes

->x{puts k=[?\s*(r=x-1)+?+]*r,?+*r+=x,k}

Try it online!

\$\endgroup\$
6
\$\begingroup\$

GNU sed, 104 99 bytes

-5 thanks to seshoumara
Includes +1 for -r

s/1//;h;:;s/(.*)1/ \12/;t;s/( *2)2(2*)/\1\n\1\2/
t;G;s/1+/&&1/;s/(.*)(\n1*)/&\n\1/;/1/!c+
y/12/++/

Takes input in unary.

Try it online!

s/1//                    # Subtract 1 from input
h                        # Hold onto input
:                        # Start loop
s/(.*)1/ \12/            #   Remove a 1, prepend a space, and append a 2
t                        # Loop until all 1s are 2s
                         # Start Loop (uses the previous label)
s/( *2)2(2*)/\1\n\1\2/   #   Shift all but the first 2 from the last line to a new line 
                         #   E.g.  "  2"      "  2"
                         #         "  222" -> "  2"
                         #                    "  22"
t                        # Loop until all 2s are on their own line
G                        # Append a newline and input
s/1+/&&1/                # Double the number of 1s and append an extra
s/(.*)(\n1*)/&\n\1/      # Copy all of the lines with 2s to the end
/1/!c+                   # If there aren't any 1s print a '+'
y/12/++/                 # Convert all 1s and 2s to +s
\$\endgroup\$
  • \$\begingroup\$ +1 You can save 5 bytes by using s/( *2)2(2*)/\1\n\1\2/ and s/(.*)(\n1*)/&\n\1/ as shown here, for a total score of 99. \$\endgroup\$ – seshoumara Apr 12 '17 at 9:22
5
\$\begingroup\$

Lua 113, 90 bytes

r,w,p=string.rep,io.read(),io.write;s=r(' ',w-1)p(r(s..'+'..'\n',w-1))p(r('+',w*2-1)..'\n')p(r(s..'+'..'\n',w-1))

r,w=string.rep,io.read()d=w*2-1;for a=1,d do print(a~=w and r(' ',w-1)..'+'or r('+',d))end
\$\endgroup\$
5
\$\begingroup\$

Python 2, 52 bytes

n=input()-1
p=(' '*n+'+\n')*n
print p+'++'*n+'+\n'+p

Try it online!

A 53-byte alternative (TIO):

n=input()-1
for c in' '*n+'+'+' '*n:print c*n+'+'+c*n
\$\endgroup\$
5
\$\begingroup\$

R, 54 bytes

Shaving off 7 bytes thanks to @Jarko Dubbeldam:

function(n){a=matrix("",y<-n*2-1,y);a[n,]=a[,n]="x";a}

previous answer:

f=function(n){a=matrix("",n*2-1,n*2-1);a[n,]="x";a[,n]="x";a}
\$\endgroup\$
  • 1
    \$\begingroup\$ You don't have to name functions, so function(n){a=matrix("",n*2-1,n*2-1);a[n,]="x";a[,n]="x";a} would be 59 bytes! \$\endgroup\$ – JAD Apr 12 '17 at 13:06
  • 1
    \$\begingroup\$ Also, you can save a byte using matrix("",y<-n*2-1,y) \$\endgroup\$ – JAD Apr 12 '17 at 13:07
  • 1
    \$\begingroup\$ a[n,]=a[,n]="x" works too, saving some more bytes. \$\endgroup\$ – JAD Apr 12 '17 at 13:08
  • \$\begingroup\$ You can save another 4 bytes by using scan() and making it a program rather than a function: n=scan();a=matrix("",y<-n*2-1,y);a[n,]=a[,n]="+";a \$\endgroup\$ – rturnbull Apr 14 '17 at 10:08
4
\$\begingroup\$

PowerShell, 48 bytes

param($n)($x=,(" "*--$n+"+")*$n);'+'*(1+2*$n);$x

Try it online!

Takes input $n. Starts by constructing a string of --$n spaces, concatenated with +. That's converted into an array using the comma operator, (newly-decremented) $n times. That array is stored in $x and encapsulated in parens to place a copy on the pipeline.

We then do the middle section, which is + string multiplied out the appropriate number of times. That's left on the pipeline. Finally, we put $x on the pipeline again.

Those are all left on the pipeline at program completion, and the implicit Write-Output inserts a newline between elements.

\$\endgroup\$
4
\$\begingroup\$

Perl 5, 45 bytes

44 bytes of code + -p flag.

$_=join"+
",@%=($"x--$_)x$_,"+"x($_*2),@%,""

Try it online!


Some similar (but still different) approaches:

48 bytes (47+-p):

$_=join"+"x($_*2-1).$/,(~~($"x--$_."+\n")x$_)x2

50 bytes (49+-n):

$,="+"x($_*2-1).$/;print+(~~($"x--$_."+\n")x$_)x2
\$\endgroup\$
4
\$\begingroup\$

Python 2, 60,56 bytes

n=input()-1
z=(' '*n+'+\n')*n
print z+'+'*(2*n+1)+'\n'+z

Try it online!

  • -4 bytes - thanks to math junkie!
\$\endgroup\$
  • 1
    \$\begingroup\$ Save 4 bytes like this: TIO \$\endgroup\$ – math junkie Apr 11 '17 at 16:35
3
\$\begingroup\$

CJam, 23 bytes

ri_(S*'++a\2*(*_z..e>N*

Try it online!

Explanation

This feels a bit suboptimal, but the idea is to superimpose the following two grids:

  +
  +
  +
  +
  +



+++++

Which gives the desired result.

ri    e# Read input and convert to integer N.
_(    e# Duplicate and decrement.
S*    e# Get a string of N-1 spaces (indentation of the vertical bar).
'++   e# Append a + (the vertical bar).
a     e# Wrap the line in an array.
\2*(  e# Swap with the other copy of N and compute 2N-1.
*     e# Repeat the line that many times.
_z    e# Duplicate the grid and transpose it.
..e>  e# Pairwise maximum between the two grids. This superimposes them.
N*    e# Join with linefeeds.
\$\endgroup\$
3
\$\begingroup\$

CJam, 17

ri(S*_]'+*_ffe>N*

Try it online

Explanation:

ri(      read n, convert to int and decrement
S*       make a string of n-1 spaces
_]       duplicate it and put the 2 strings in an array
'+*_     join the strings with a '+' and duplicate the result
ffe>     for each pair of characters from the 2 (identical) strings,
          get the larger character (results in a matrix)
N*       join the rows with newlines
\$\endgroup\$
3
\$\begingroup\$

Octave, 36 31 bytes

Inspired by @LuisMendo 's MATL answer.

@(n)' +'(((a=1:n*2-1==n)|a')+1)

Try it online!

Previous answer:

@(n)' +'(1+((a=padarray(1,n-1))|a'))

Try it online!

\$\endgroup\$
3
\$\begingroup\$

05AB1E, 15 14 12 bytes

F'+}¹·<×)û.c

Try it online!

-2 thanks to Emigna.

\$\endgroup\$
  • 1
    \$\begingroup\$ You could do F'+}¹·<×)û.c for 12. \$\endgroup\$ – Emigna Apr 11 '17 at 20:22
  • \$\begingroup\$ Your try it online link is bad - it doesn't link to the current revision of the post so it shows "bad output" that doesn't match the test cases above. \$\endgroup\$ – Thomas Ward Apr 12 '17 at 4:41
  • \$\begingroup\$ @ThomasWard: Good catch! I corrected the link. \$\endgroup\$ – Emigna Apr 12 '17 at 6:35
2
\$\begingroup\$

Python 2, 65 bytes

lambda n:('g+\n'*~-n+'+'*~-(2*n)+'\ng+'*~-n).replace('g',' '*~-n)

Try it Online!

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

JS (ES6), 88 74 73 bytes

x=>(x--,y=y=>(" ".repeat(x)+`+
`).repeat(x),y``+"+".repeat(x+x+1)+"\n"+y``)

Probably can be golfed more.

Snippetify(x=>(x--,y=y=>(" ".repeat(x)+`+
`).repeat(x),y``+"+".repeat(x+x+1)+"\n"+y``))
<script src="https://programmer5000.com/snippetify.min.js"></script>
<input type = "number">
<pre data-output></pre>

\$\endgroup\$
  • 1
    \$\begingroup\$ I'm not entirely sure, but I think you can replace the "\n" with two backticks and a literal newline between them \$\endgroup\$ – Kritixi Lithos Apr 11 '17 at 15:54
  • \$\begingroup\$ Only seeing this solution now, you beat me by a few minutes. What's the etiquette around here on similar solutions in the same language that are posted within a small window of time? \$\endgroup\$ – Shaggy Apr 11 '17 at 16:44
2
\$\begingroup\$

JavaScript (ES6), 60 bytes

f=
n=>(r=([s,t])=>(s=s.repeat(n-1))+t+s+`
`)([r(` +`),r(`++`)])
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

Outputs two trailing newlines. Alternative formulation, also 60 bytes:

n=>(r=a=>(s=a[0].repeat(n-1))+a[1]+s+`
`)([r(` +`),r(`++`)])
\$\endgroup\$
2
\$\begingroup\$

PowerShell, 48

Doesn't seem to get shorter than that (and pretty much the same approach as the other solution):

($a=,(' '*($n="$args"-1)+'+')*$n)
'+'+'++'*$n
$a

or

($a=(' '*($n="$args"-1)+'+
')*$n)+'++'*$n+"+
$a"
\$\endgroup\$
2
\$\begingroup\$

V, 19 18 15 bytes

Golfed 3 bytes thanks to @nmjcman101 by using . and Ò+

Àé r+À«Ä.MgJxÒ+

Try it online!

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

REXX, 81 bytes

arg a
b=a*2-1
do i=1 to b
  if i=a then say copies('+',b)
  else say right('+',a)
  end
\$\endgroup\$
2
\$\begingroup\$

PHP, 68 Bytes

for(;$i<$c=-1+2*$m=$argn;)echo"\n".str_pad("+",$c," +"[$m==++$i],2);

83 Bytes

for(;$i<($c=($n=$argn)*2-1)**2;)echo$i%$c?"":"\n".!++$k," +"[$k==$n|$i++%$c==$n-1];
\$\endgroup\$
  • 1
    \$\begingroup\$ You can save a few bytes by using $m=$argn and pre-incrementing $i rather than post incrementing it. you can also save a byte by moving the $m assignment ot the end and dropping the brackets. \$\endgroup\$ – user59178 Apr 12 '17 at 8:38
  • \$\begingroup\$ @user59178 I could not understand what you exactly mean \$\endgroup\$ – Jörg Hülsermann Apr 12 '17 at 9:50
  • 1
    \$\begingroup\$ for(;$i<$c=-1+2*$m=$argn;)echo"\n".str_pad("+",$c," +"[$m==++$i],2); \$\endgroup\$ – user59178 Apr 12 '17 at 12:00
  • \$\begingroup\$ while(++$y<2*$n=$argn)echo"\n",str_pad("+",$n*2-1," +"[$y==$n],2); 66 bytes (and save one more with a physical linebreak) \$\endgroup\$ – Titus Aug 14 '17 at 17:47
2
\$\begingroup\$

MUMPS, 48 50 53 bytes

F i=1-n:1:n-1 W ! F j=1-n:1:n-1 W $C(i&j*-11+43)
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Apr 11 '17 at 21:38
2
\$\begingroup\$

Brain-Flak, 216 + 1 = 217 bytes

+1 bytes from the -A flag

([{}]())(()()){<>(((((()()()()()){})){}()){}())<>(({}[()])<({}<(({})){({}()<(({}<<>(({}<(({})<>)>)<>)<>>)<{({}()<(((((()()){}){}){}){})>)}{}>)>)}{}>){(<{}(({}<<>({}<({}<>)>)>)<(({}){}){({}()<(({}))>)}{}>)>)}{}>)}{}{}

Try it online!

Explanation to come

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