Challenge :

Given an integer n as input. Create a diamond that is 2x the given number n.

Input :

Input is integer n and 2 < n ≤ 3000.

Output :

Output will be a string and it will be in form of a diamond consisting of + with an addition line at the start showing n using +

Examples :

D(3) :

+++
  +
 +++
+++++
+++++
 +++
  +

D(5) :

+++++
    +
   +++
  +++++
 +++++++
+++++++++
+++++++++
 +++++++
  +++++
   +++
    +

D(6) : 

++++++
     +
    +++
   +++++
  +++++++
 +++++++++
+++++++++++
+++++++++++
 +++++++++
  +++++++
   +++++
    +++
     +

Winning Criteria :

This is so shortest code in bytes for each programming language wins.

42 Answers 42

brainfuck, 151 139 bytes

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

Try it online!

Takes input via unary, with +s as tally marks (allowed by the poster). Decided to rework this, as I thought the old one was a bit longer than it could be (though this one is too!).

Old Version (151 bytes):

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

Try it online!

Takes input as the starting cell. I couldn't think of a way to leverage the first half to help with the second, so there's a loop for each of them.

How It Works:

 >--[>+<++++++]  Create 43 ('+') two space to the left of n
 <[->+>.<<]      Print n '+'s while preserving n
 ++++++++[-<+<++++>>]<++  Create 32 (' ') and 10 ('\n')
                         Tape: 32 10 0 n 43 t
 >>
 [ Loop over the first half of the diamond
   <<.>>         Print a newline
   -[-<+<<.>>>]  Decrement n and print n spaces
   <[->+<]       Restore n
   >>>+[-<.>>+<] Increment t and print t '+'s
   >+[-<+>]<<<   Increment t again and restore it
]>>
[ Loop over the second half
  <<<<.>>        Print a newline
  [-<+<<.>>>]<   Print n spaces
  [->+<]>+       Restore and increment n
  >>-[-<.>>+<]   Decrement t and print t '+'s
  >-[-<+>]<      Decrement t again and restore it
]

And just for fun:

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

Try it online!

  • 2
    You got my vote for the just for the fun thing. Cool answer – Muhammad Salman Apr 20 at 11:32

Canvas, 9 bytes

+×O{+×]±╪

Try it here!

Explanation (some characters have been replaced to look monospace):

+×O{+×]±╪
+×         repeat "+" input times
  O        output that
   {  ]    map over 1..input
    +×       repeat "+" that many times
       ±   interpret the array as a 2D string, and reverse it
        ╪  quad-palindromize with 1 horizontal overlap and 0 vertical overlap

Python 3, 95 94 75 bytes

def f(n):a=[' '*(n+~i)+'+'*(i-~i)for i in range(n)];return['+'*n]+a+a[::-1]

Try it online!


My first attempt at some golfing, any suggestions for improvement are welcome.

EDIT: saved 1 byte thanks to Kevin Cruijssen

EDIT: removed misunderstanding about byte count

EDIT: Saved many more bytes thanks to Jo King and user202729

  • 5
    Welcome to PPCG! :) – Shaggy Apr 19 at 7:36
  • 1
    Also, if you change to Python 2, print'\n'.join(['+'*n]+a+a[::-1]) can be used without parenthesis to save 2 more bytes. +1 from me though. Nice first answer. :) – Kevin Cruijssen Apr 19 at 7:57
  • 1
    Submissions can be either a full program (nothing in header/footer) or a function (which must defines a function (or reference, in case of anonymous function such as lambda)). – user202729 Apr 19 at 14:28
  • 2
    And, 2*i+1 == i+i+1 == i-(-i-1) == i-~i. – user202729 Apr 19 at 14:30
  • 2
    Great first answer. well done. – ElPedro Apr 19 at 19:10

05AB1E, 14 bytes

'+×sL·<'+×∊.c»

Try it online!

Explanation

'+×              # push "+" repeated <input> times
   sL            # push range [1 ... input]
     ·<          # multiply each element by 2 and decrement (x*2-1)
       '+×       # replace each number with the corresponding number of "+"'s
          ∊      # mirror vertically
           .c    # center
             »   # join with the "+"-row created at the start

Also 14 bytes: L‚˜'+×ćs.∞∊.c»

  • 1
    '+×s·ÅÉ'+×∊.C» using ÅÉ is another – Magic Octopus Urn Apr 19 at 14:21
  • @MagicOctopusUrn: My initial thought was using ÅÉ but I discarded it because I didn't think of using · to make it work. – Emigna Apr 19 at 15:36

Python 3, 79 78 bytes

def f(n):x=[('++'*i+'+').center(n*2)for i in range(n)];return[n*'+']+x+x[::-1]

Try it online!

Thanks to this Tips for golfing Python answer for informing me about the .center function. Returns a list of strings.

  • Isn't the footer included in the byte count? In that case, my solution is 58 bytes – maxb Apr 19 at 9:12
  • @maxb If you're using a function, it is generally okay to return output as a list of lines – Jo King Apr 19 at 11:08
  • @JoKing : Hum might wanna do a lil recheck ? TRY – Muhammad Salman Apr 19 at 12:04
  • @JoKing : It fails. – Muhammad Salman Apr 19 at 12:04
  • 1
    @MuhammadSalman 1. You’re testing my function for n=3 against the return for n=5, 2. You have a trailing newline in the test, and 3. My code has trailing spaces on each line. Maybe you should just look at the output next time – Jo King Apr 19 at 12:16

R, 135 110 96 bytes

function(n){cat("+"<n,"
",sep="")
for(i in c(1:n,n:1))cat(" "<n-i,"+"<2*i-1,"
",sep="")}
"<"=rep

Try it online!

@JayCe with the final cut.

The rep function is assigned to an existing infix operator, such as < or ^ so that rep("+", n) is equivalent to "<"("+", n) which can be written out using < as an infix operator as in "+" < n and shortened to "+"<n.

  • 1
    Save 25 bytes and make it a function. – JayCe May 2 at 2:16
  • So totally your answer :) Great original code! – JayCe May 2 at 23:06
  • There's some whitespace here that can be removed, and using "+" directly instead of saving it as z saves some bytes! Try it here – Giuseppe May 5 at 12:28
  • 1
    @ngm @Giuseppe On top of Giuseppe's improvement, substitute < for rep to get under 100 chars! Here – JayCe May 16 at 16:22

Charcoal, 15 bytes

G→→↙N+↓‖M↑×⊕ⅈ+‖

Try it online! Link is to verbose version of code. Explanation:

G→→↙N+

Print an inverted triangle of +s the height of the input and almost twice the width.

Move the cursor down so it lands on the additional line after the reflection.

‖M↑

Make a mirror image of the triangle.

×⊕ⅈ+

Draw the additional line using the current column to avoid having to read the input again.

Reflect the output so that the additional line points to the left.

Python 3, 76 75 bytes

lambda n:['+'*n]+[' '*(n+~i)+'+'*(i-~i)for i in[*range(n),*range(n)[::-1]]]

Try it online!

QB64, 82 79 bytes

INPUT n
?STRING$(n,43):FOR a=1TO 2*n:d=a-(a>n)*2*(n-a):?SPC(n-d);STRING$(2*d-1,43):NEXT
  • 3
    Welcome to PPCG! This is a great first submission, and I've added it to the list of solutions posted while QBasic is Language of the Month. If you like, you can improve this answer by adding a short explanation. Enjoy your time here! – DLosc Jun 1 at 22:43

Stax, 11 bytes

ñ1┌╙@↔g+┤a☻

Run and debug it

JavaScript (Node.js), 106 105 bytes

  • thanks to @Kevin Cruijssen for reducing by 1 byte
n=>[...Array(n*2+1)].map((_,i)=>" ".repeat(i?i>n?i+~n:n-i:0)+"+".repeat(i?i>n?4*n-2*i+1:i*2-1:n)).join`
`

Try it online!

________________________________________________

Second approach

JavaScript (Node.js), 105 100 99 98 bytes

  • thanks to @Kevin Cruijssen for reducing by 1 byte
  • thanks to @ovs for reducing by 1 byte
n=>[X="+"[r="repeat"](n),...x=[...X].map((_,i)=>" "[r](n+~i)+"+"[r](i-~i)),...x.reverse()].join`
`

Try it online!

  • 2
    Just as a matter of convention, you should have your shortest submission at the top of your post if you have multiple approaches within it. This allows for other people to easily attempt the challenge, search for their language, and see how they compare to your best answer (and is needed for scoreboards to work properly on challenges that have scoreboards) – Taylor Scott May 18 at 16:20

PowerShell, 55 bytes

param($l)'+'*$l;1..$l+$l..1|%{" "*($l-$_)+'+'*($_*2-1)}

Try it online!

  • 1
    Great answer but the character should be + instead of x. Also you can make your response a bit more community friendly by using Try it online! and adding a link to your answer – Taylor Scott Apr 19 at 21:38
  • 1
    Derp - can't believe I didn't see that. Thanks! – Tor Apr 19 at 21:48

J, 29 bytes

'+'(,]\(}:@|."1,.])@,]\.)@$~]

Try it online!

Explanation:

'+'$~] - generates the line at the start, which is a seed for the diamond:

   '+'$~]  3
+++

]\,]\. - finds the prefixes (]\) and suffixes (]\.) of the line, making "half" the diamond 

   '+'(]\,]\.)@$~] 3
+  
++ 
+++
+++
++ 
+  

}:@|."1,.] - makes the other "half" of the diamond by reversing each line (|."1)
and dropping its last '+' (}:) and stitches the first half to it (,.])

 '+'(]\(}:@|."1,.])@,]\.)@$~] 3
  +  
 +++ 
+++++
+++++
 +++ 
  +  

, - prepends the initial line to the diamond

'+'(,]\(}:@|."1,.])@,]\.)@$~] 3
+++  
  +  
 +++ 
+++++
+++++
 +++ 
  +  

Haskell, 85 82 bytes

Saved 3 bytes thanks to nimi!

n!c=[1..n]>>c
f n|x<-[(n-i)!" "++(i*2-1)!"+"|i<-[1..n]]=unlines$n!"+":x++reverse x

Try it online!

Ruby, 71 61 bytes

->n{[?+*n]+(a=(1..n).map{|x|?\s*(n-x)+?+*(x+x-1)})+a.reverse}

Try it online!

PHP, 103 bytes

for(;$i++<$argn;$s.="
".str_pad(str_pad("",$i*2-1,"+",2),$argn*2-1," ",2))echo"+";echo"$s
",strrev($s);

Run as pipe with `-nR´ or try it online.

PowerShell, 58 bytes

param($n)'+'*$n;1..$n+$n..1|%{" "*($n-$_)+"+"*$_+"+"*--$_}

Try it online!

Simply a loop-up and -down, each iterating outputting the appropriate number of spaces and then the appropriate number of plus signs. Ho-hum.

Japt -R, 18 17 bytes

õÈ+Y î+Ãû ê1 iUî+

Try it online!

F# (Mono), 123 bytes

let d n=
 let t n=String('+',n)
 let s n=t(n*2-1)
 [1..n]@[n.. -1..1]|>Seq.fold(fun a x->a+sprintf"\n%*s"(n+x-1)(s x))(t n)

Try it online!

  • 4
    Welcome to PPCG. – Muhammad Salman Apr 19 at 15:09
  • This doesn't appear to work. Also, input should be taken from STDIN, a file, or a function argument. We don't allow pre-assigned variables as input. – mbomb007 Apr 19 at 15:23
  • @mbomb007 Can you approve it now? – Henrik Hansen Apr 19 at 15:32
  • @HenrikHansen : Why is this giving an error ? /home/runner/code.fs(2,10): error FS0039: The value or constructor 'String' is not defined. Cannot open assembly 'code.exe': No such file or directory. – Muhammad Salman Apr 19 at 15:44
  • 1
    @HenrikHansen : I suggested an edit. Take a look – Muhammad Salman Apr 19 at 16:06

PHP 102 bytes

for($r=str_pad;$i++<$a;$s.="\n".$r($r("",$i*2-1,"+",2),$a*2-1," ",2))echo"+";echo"$s\n",strrev($s);

Ik know it can be much smaller than this ;) Greetz mangas

  • Welcome to PPCG! – Muhammad Salman Apr 19 at 16:40
  • Your code seems to produce an error when I try to run it? – Muhammad Salman Apr 19 at 16:44
  • Why did you suggest this as a separate edit? It makes no sense. – Stephen Leppik Apr 19 at 17:08
  • @StephenLeppik : Oops , probably a mistake on my part. Soory – Muhammad Salman Apr 19 at 17:21

sed 4.2.2, 69

Score includes +1 for the -r option to sed.

h
y/1/+/
p
x
s/1\B/ /g
y/1/+/
p
:
s/ \+/+++/p
t
p
:a
s/\+\+/ /p
ta
d

Try it online!

Ruby, 59 bytes

->i{[?+*i,b=(1..i).map{|c|' '*(i-c)+?+*(2*c-1)},b.reverse]}

Try it online!

Python 3, 98 bytes

def d(s):print("+"*s);t=[("+"*i).center(2*s-1)for i in range(1,2*s,2)];print("\n".join(t+t[::-1]))

Try it online!

Readable version:

def diamond(size):
    print(size * "+")
    top = [("+" * i).center(2*size - 1) for i in range(1, 2*size, 2)]
    print("\n".join(top))
    print("\n".join(reversed(top)))
  • Much better :) I formatted your entry so that it looks like other answers. You want want to visit tio.run it formats your answer for you and makes it easy for others to reproduce your code. – JayCe May 16 at 22:35

Yabasic, 102 bytes

An anonymous function that takes input as a unary number with + tally marks and outputs to the console.

Input""s$
n=Len(s$)
?s$
For i=-n To n
j=Abs(i)
If i For k=2To j?" ";Next:?Mid$(s$+s$,1,2*(n-j)+1)
Next

Try it online!

Alternate Version, 117 bytes

An anonymous function answer that takes input as a decimal integer and outputs to the console.

Input""n
For i=1To n s$=s$+"+"Next
?s$
For i=-n To n
j=Abs(i)
If i For k=2To j?" ";Next:?Mid$(s$+s$,1,2*(n-j)+1)
Next

Try it online!

  • Anonymous functions? They look like whole programs to me... – Ørjan Johansen May 18 at 16:10
  • @ØrjanJohansen this term, for Yabasic, only means that they are not wrapped as a user defined subroutine, are not part of any library and thus cannot be called discretely like builtin functions can be (eg. Abs(x)) . You can read a bit more about this here if you like. – Taylor Scott May 18 at 18:10

JavaScript (Node.js), 183 bytes

a=x=>{g='\n';r=(m,n)=>String.prototype.repeat.call(m,n);k='+';l=r(k,x)+g;c=d='';for(i=0;i++<x;c+=r(' ',x-i)+r(k,i)+r(k,i-1)+g,d+=r(' ',i-1)+r(k,x+1-i)+r(k,x-i)+g);console.log(l+c+d);}

Try it online!

Updated my answer thanks to @JoKing

  • @JoKing sorry, my mistake, I just update my answer, thank you my friend. – NTCG May 15 at 9:04
  • @JoKing, thank you for your time – NTCG May 15 at 23:47

Java 8, 159 bytes

n->{String r="",N="\n",t=r;for(int i=n,j,k;i-->0;t+="+",r+=i>0?N:"")for(j=-n;++j<n;r+=k<n?"+":" ")k=i+(j<0?-j:j);return t+N+r+N+new StringBuffer(r).reverse();}

Can definitely be golfed some more, but it's a start.

Explanation:

Try it online.

n->{                    // Method with integer parameter and String return-type
  String r="",          //  Result-String, starting empty
         N="\n",        //  Temp-String for new-line to save bytes
         t=r;           //  First-line String, starting empty
  for(int i=n,j,k;i-->0 //  Loop `i` in the range (n,0]
      ;                 //    After every iteration:
       t+="+",          //     Append a "+" to the first-line String
       r+=i>0?N:"")     //     Add a new-line if this isn't the last iteration of `i` yet
    for(j=-n;++j<n;     //   Inner loop `j` in the range (-n,n]
        r+=             //     After every iteration, append the result with:
           k<n?         //      If `k` is smaller than the input `n`:
            "+"         //       Append a "+"
           :            //      Else:
            " ")        //       Append a space instead
      k=i+(j<0?-j:j);   //    Set `k` to `i` plus the absolute value of `j`
  return t+N            //  Return the first-line String plus new-line,
         +r+N           //   plus the result-String plus new-line,
         +new StringBuffer(r).reverse();}
                        //   plus the result-String again reversed

Japt -R, 18 16 bytes

õ_ç+ êÃê1 û i+pU

Try it


Explanation

                     :Implicit input of integer U
õ                    :Range [1,U]
 _    Ã              :Pass each Z through a function
  ç+                 :  Repeat "+" Z times
     ê               :  Palindromise
       ê1            :Mirror
          û          :Centre pad each element to the length of the longest element
            i        :Prepend
             +pU     :  "+" repeated U times
                     :Implicitly join with newlines and output

Attache, 62 bytes

{"+"*_+lf+UnGrid!Bounce=>"+ "[Table[`>,1:_]|>~`'#Reverse|>@N]}

Try it online!

A lambda which takes the integer as an argument.

Example

A> n := 3
3
A> Table[`>,1:n]
 false false false
  true false false
  true  true false
A> Table[`>,1:n]|>~`'#Reverse
  true  true false
  true false false
 false false false
 false false false
  true false false
  true  true false
A> Table[`>,1:n]|>~`'#Reverse|>@N
 1 1 0
 1 0 0
 0 0 0
 0 0 0
 1 0 0
 1 1 0
A> "+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
 " " " " "+"
 " " "+" "+"
 "+" "+" "+"
 "+" "+" "+"
 " " "+" "+"
 " " " " "+"
A> Bounce=>"+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
 " " " " "+" " " " "
 " " "+" "+" "+" " "
 "+" "+" "+" "+" "+"
 "+" "+" "+" "+" "+"
 " " "+" "+" "+" " "
 " " " " "+" " " " "
A> UnGrid!Bounce=>"+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
"  +  \n +++ \n+++++\n+++++\n +++ \n  +  "
A> lf+UnGrid!Bounce=>"+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
"\n  +  \n +++ \n+++++\n+++++\n +++ \n  +  "
A> "+"*n+lf+UnGrid!Bounce=>"+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
"+++\n  +  \n +++ \n+++++\n+++++\n +++ \n  +  "
A> Print[_]
+++
  +
 +++
+++++
+++++
 +++
  +
["+++\n  +  \n +++ \n+++++\n+++++\n +++ \n  +  "]
A>

T-SQL, 152 bytes

Per our IO rules, input is taken via pre-existing table t with a integer field n.

DECLARE @n INT,@ INT=1,@k INT=1SELECT @n=n FROM t
PRINT REPLICATE('+',@n)a:PRINT SPACE(@n-@)+REPLICATE('+',2*@-1)IF @=@n SET @k-=1SET @+=@k IF @>0GOTO a

Manual counting loop, not very "SQL-like". Formatted:

DECLARE @n INT,@ INT=1,@k INT=1
SELECT @n=n FROM t
PRINT REPLICATE('+',@n)
a:
    PRINT SPACE(@n-@)+REPLICATE('+',2*@-1)
    IF @=@n SET @k-=1
    SET @+=@k
IF @>0 GOTO a

V, 20 bytes

é+ÄÀ­ñ>GMÙX2é+ÄHñÄÒ+

Try it online!

Hexdump:

00000000: e92b c4c0 adf1 3e47 4dd9 5832 e92b c448  .+....>GM.X2.+.H
00000010: f1c4 d22b                                ...+

Explanation:

é+                      " Insert a '+' character
  Ä                     " Duplicate this line
   À­                   " 'arg' - 1 times...
     ñ          ñ       " Repeat the following code:
      >G                "   Indent every line
        M               "   Move to the center line
         Ù              "   Duplicate this line
          X             "   Delete the first character of it (the space)
           2é+          "   Insert two '+' characters
              Ä         "   Duplicate this new line we made
               H        "   Return to the first line
                 Ä      " After the loop is over, duplicate the top line
                  Ò+    " Replace every character on this line with a '+'

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.