Diamond creator +

27

1

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.

Muhammad Salman

Posted 2018-04-19T06:57:16.527

Reputation: 2 361

Related: Print this diamond and related: User Scored Code Golf - Drawing Diamonds – Kevin Cruijssen – 2018-04-19T06:58:15.060

@KevinCruijssen : Um so is this ok , or should I remove this ? – Muhammad Salman – 2018-04-19T06:59:36.750

No it's ok. It's related, not a duplicate. :) Related challenges are just linked as inspiration, but yours is different enough (imo) to not be closed as a dupe. – Kevin Cruijssen – 2018-04-19T07:00:02.947

@KevinCruijssen : Ok so it can stay ? – Muhammad Salman – 2018-04-19T07:00:44.517

@KevinCruijssen : I see , i'm still new so learning the rules , thanks for telling me. – Muhammad Salman – 2018-04-19T07:01:44.547

1May we take n in unary? – Adám – 2018-04-19T07:16:09.027

3

… using + as tally mark?

– Adám – 2018-04-19T07:17:10.093

@Adám : I guess you can if you feel like the normal doesn't work – Muhammad Salman – 2018-04-19T07:32:10.120

1Can you add a test case where n is even? – Shaggy – 2018-04-19T10:09:00.943

2@Shaggy : sure why not. I will add that right away. Thanks – Muhammad Salman – 2018-04-19T10:11:02.880

@Shaggy : There implemented. – Muhammad Salman – 2018-04-19T10:12:23.000

1

@Adám here is the meta post on unary I/O

– Digital Trauma – 2018-04-19T17:45:48.357

1This is a grenade. – Tamás Sengel – 2018-04-21T23:12:00.970

Answers

33

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!

Jo King

Posted 2018-04-19T06:57:16.527

Reputation: 38 234

2You got my vote for the just for the fun thing. Cool answer – Muhammad Salman – 2018-04-20T11:32:15.873

15

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

dzaima

Posted 2018-04-19T06:57:16.527

Reputation: 19 048

12

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

maxb

Posted 2018-04-19T06:57:16.527

Reputation: 5 754

5Welcome to PPCG! :) – Shaggy – 2018-04-19T07:36:33.057

1Also, 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 – 2018-04-19T07:57:19.263

Wow, I didn't know that the ~ operator worked like that for integers. I'll stick to Python 3 for now, as I have very limited experience with Python 2, and someone else could probably come up with a better solution. Thanks for the help! – maxb – 2018-04-19T08:35:46.347

Your byte-count is wrong (was correct previously). If you define a function that returns the result, you can use the footer to call that function and display the result. You can't do part of the challenge in the footer and not count those bytes. – Emigna – 2018-04-19T09:20:41.110

I reverted to the previous edit. I was just a bit confused as the other Python answer had a bit of logic in the footer, I'll try to read up on the rules. – maxb – 2018-04-19T10:15:25.437

@JoKing I saw that you used that approach in your answer, is there any consensus on what is allowed in the footer and what isn't? – maxb – 2018-04-19T13:52:28.697

1Submissions 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 – 2018-04-19T14:28:07.063

In this case it's allowed to return a list of lines. – user202729 – 2018-04-19T14:29:12.303

2And, 2*i+1 == i+i+1 == i-(-i-1) == i-~i. – user202729 – 2018-04-19T14:30:04.247

2Great first answer. well done. – ElPedro – 2018-04-19T19:10:31.383

9

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»

Emigna

Posted 2018-04-19T06:57:16.527

Reputation: 50 798

1'+×s·ÅÉ'+×∊.C» using ÅÉ is another – Magic Octopus Urn – 2018-04-19T14:21:49.390

@MagicOctopusUrn: My initial thought was using ÅÉ but I discarded it because I didn't think of using · to make it work. – Emigna – 2018-04-19T15:36:34.880

5

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.

Jo King

Posted 2018-04-19T06:57:16.527

Reputation: 38 234

Isn't the footer included in the byte count? In that case, my solution is 58 bytes – maxb – 2018-04-19T09:12:18.150

@maxb If you're using a function, it is generally okay to return output as a list of lines – Jo King – 2018-04-19T11:08:12.127

@JoKing : Hum might wanna do a lil recheck ? TRY

– Muhammad Salman – 2018-04-19T12:04:04.077

@JoKing : It fails. – Muhammad Salman – 2018-04-19T12:04:16.640

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 – 2018-04-19T12:16:19.573

@JoKing : 1). oops. My bad forgot to change it back to 5. 2). Hum , well I guess that works too. Cool – Muhammad Salman – 2018-04-19T12:29:59.210

@JoKing : Apologies for inconvenience – Muhammad Salman – 2018-04-19T12:30:27.717

You can do this in 75 bytes by calculating the number of spaces: def f(n):x=[' '*(n+~i)+'++'*i+'+'for i in range(n)];return[n*'+']+x+x[::-1] – ovs – 2018-04-19T14:33:15.793

Eh, it ends up being a copy of maxb's answer – Jo King – 2018-04-20T02:15:59.443

4

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.

ngm

Posted 2018-04-19T06:57:16.527

Reputation: 3 974

1Save 25 bytes and make it a function. – JayCe – 2018-05-02T02:16:31.693

So totally your answer :) Great original code! – JayCe – 2018-05-02T23:06:52.837

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 – 2018-05-05T12:28:50.030

1

@ngm @Giuseppe On top of Giuseppe's improvement, substitute < for rep to get under 100 chars! Here

– JayCe – 2018-05-16T16:22:22.810

3

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.

Neil

Posted 2018-04-19T06:57:16.527

Reputation: 95 035

3

Python 3, 76 75 bytes

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

Try it online!

Kirill L.

Posted 2018-04-19T06:57:16.527

Reputation: 6 693

3

Stax, 11 bytes

ñ1┌╙@↔g+┤a☻

Run and debug it

recursive

Posted 2018-04-19T06:57:16.527

Reputation: 8 616

3

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

Corwin Fjeldstrom

Posted 2018-04-19T06:57:16.527

Reputation: 31

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 – 2018-06-01T22:43:40.950

2

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!

DanielIndie

Posted 2018-04-19T06:57:16.527

Reputation: 1 220

2Just 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 – 2018-05-18T16:20:48.677

2

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
+++  
  +  
 +++ 
+++++
+++++
 +++ 
  +  

Galen Ivanov

Posted 2018-04-19T06:57:16.527

Reputation: 13 815

2

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!

Cristian Lupascu

Posted 2018-04-19T06:57:16.527

Reputation: 8 369

Using this tip you can get rid of the twice used variable x which saves 4 bytes: Try it online!

– ბიმო – 2018-12-24T02:57:40.287

2

Japt -R, 18 17 bytes

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

Try it online!

Oliver

Posted 2018-04-19T06:57:16.527

Reputation: 7 160

2

PowerShell, 55 bytes

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

Try it online!

Tor

Posted 2018-04-19T06:57:16.527

Reputation: 201

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 – 2018-04-19T21:38:01.443

1Derp - can't believe I didn't see that. Thanks! – Tor – 2018-04-19T21:48:56.853

1

Ruby, 71 61 bytes

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

Try it online!

user79855

Posted 2018-04-19T06:57:16.527

Reputation:

1

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.

Titus

Posted 2018-04-19T06:57:16.527

Reputation: 13 814

1

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.

AdmBorkBork

Posted 2018-04-19T06:57:16.527

Reputation: 41 581

1

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!

Henrik Hansen

Posted 2018-04-19T06:57:16.527

Reputation: 191

4Welcome to PPCG. – Muhammad Salman – 2018-04-19T15:09:28.517

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 – 2018-04-19T15:23:24.957

@mbomb007 Can you approve it now? – Henrik Hansen – 2018-04-19T15:32:26.093

@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 – 2018-04-19T15:44:28.987

@HenrikHansen : great the error is gone but now Main module of program is empty: nothing will happen when it is run. You should probably look into it as well – Muhammad Salman – 2018-04-19T15:49:06.197

@MuhammadSalman You can include(open) certain standard libraries or provide the full namespace path. I anticipated that is was alright to anticipate that the System library is loaded. – Henrik Hansen – 2018-04-19T15:49:53.427

@HenrikHansen : I don't know anything about F#. Except its name. Maybe this will help : https://codegolf.stackexchange.com/questions/16116/tips-for-golfing-in-f

– Muhammad Salman – 2018-04-19T15:52:24.413

@HenrikHansen The error is because of the first line. You should read input n from STDIN. What's the best way to read from stdin?. Either that, or the syntax for a multiline function is wrong. I don't know F#.

– mbomb007 – 2018-04-19T15:56:28.710

1@HenrikHansen : I suggested an edit. Take a look – Muhammad Salman – 2018-04-19T16:06:42.743

1

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

mangas

Posted 2018-04-19T06:57:16.527

Reputation: 111

Welcome to PPCG! – Muhammad Salman – 2018-04-19T16:40:10.027

Your code seems to produce an error when I try to run it? – Muhammad Salman – 2018-04-19T16:44:50.903

Why did you suggest this as a separate edit? It makes no sense. – Nissa – 2018-04-19T17:08:20.783

@StephenLeppik : Oops , probably a mistake on my part. Soory – Muhammad Salman – 2018-04-19T17:21:10.583

1

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!

Taylor Scott

Posted 2018-04-19T06:57:16.527

Reputation: 6 709

Anonymous functions? They look like whole programs to me... – Ørjan Johansen – 2018-05-18T16:10:37.560

@Ø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 – 2018-05-18T18:10:15.157

1

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!

Digital Trauma

Posted 2018-04-19T06:57:16.527

Reputation: 64 644

1

Ruby, 59 bytes

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

Try it online!

lfvt

Posted 2018-04-19T06:57:16.527

Reputation: 121

1

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

NTCG

Posted 2018-04-19T06:57:16.527

Reputation: 151

@JoKing sorry, my mistake, I just update my answer, thank you my friend. – NTCG – 2018-05-15T09:04:40.417

@JoKing, thank you for your time – NTCG – 2018-05-15T23:47:53.673

1

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)))

SlayerGames44

Posted 2018-04-19T06:57:16.527

Reputation: 33

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 – 2018-05-16T22:35:05.427

1

APL (Dyalog Unicode), 25 bytesSBCS

⍪∘⊖⍨c,⍨⌽1↓[2]c←↑,\⎕←⎕/'+'

Try it online!

Explanation:

⍪∘⊖⍨c,⍨⌽1↓[2]c←↑,\⎕←⎕/'+'  ⍝ Full program
                       ⎕/'+'  ⍝ Get input from user as N, replicate '+' N times
                    ⎕←        ⍝ Print above string
                  ,\           ⍝ Find all prefixes of above string, e.g. '+','++','+++' etc.
                 ↑             ⍝ Mix the above into a matrix - right-pads with spaces as needed
               c←              ⍝ Assign above matrix to 'c' for 'corner'
          1↓[2]                ⍝ Drop the first column
        ⌽                     ⍝ Reverse the resulting matrix
     c,⍨                      ⍝ Append 'c' to above - this gives us the top half
⍪∘⊖⍨                         ⍝ Take the above, flip it about the horizontal axis,
                              ⍝ and append it to itself

voidhawk

Posted 2018-04-19T06:57:16.527

Reputation: 1 796

1↓[2] -> 0 1↓ or even better: c,⍨⌽1↓[2]c← -> ⍉(⊖⍪1↓⊢)⍉ – ngn – 2019-03-11T07:36:18.987

0

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

Shaggy

Posted 2018-04-19T06:57:16.527

Reputation: 24 623

0

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

Kevin Cruijssen

Posted 2018-04-19T06:57:16.527

Reputation: 67 575

0

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>

Conor O'Brien

Posted 2018-04-19T06:57:16.527

Reputation: 36 228

0

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

BradC

Posted 2018-04-19T06:57:16.527

Reputation: 6 099

0

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 '+'

James

Posted 2018-04-19T06:57:16.527

Reputation: 54 537

0

Excel VBA, 89 bytes

Anonymous VBE immediate window function that takes input as a unary number with + tally marks from range [A1] (ie [A1]="++++") that outputs to the VBE immediate window.

?[A1]:n=[Len(A1)]:For i=-n To n:i=i-(i=0):j=Abs(i):?Spc(j-1)Mid([A1&A1],1,2*(n-j)+1):Next

Alternate Version, 96 bytes

Anonymous VBE immediate window function that takes input as a decimal number from range [A1] that outputs to the VBE immediate window.

?[Rept("+",A1)]:For i=[-A1]To[A1]:i=i-(i=0):[B1]=Abs(i):?Spc([B1]-1)[Rept("+",2*(A1-B1)+1)]:Next

Taylor Scott

Posted 2018-04-19T06:57:16.527

Reputation: 6 709

0

Phooey, 82 bytes

&.@@($c43-1)&>&1<[-1$c10@[-1$c32]&>@[-1$c43]&+2<][!$c10@[-1$c32]&+1>-2@[-1$c43]&<]

Try it online!

Phooey is an extended form of Foo, adding input, sane loops, and some helper functions.

Conor O'Brien

Posted 2018-04-19T06:57:16.527

Reputation: 36 228

0

Swift, 218 169 bytes

Sadly, I could not use map instead of for loops, since it timed out.

func r(i:Int)->String{var l="";for j in(0...i*2){for k in(0..<i*2-1){l+=j==0&&k<i||j>0&&(j>i ?j-i-1:i-j)...(j>i ?i*3-1-j:i+j-2)~=k ?"+":" "};if j<i*2{l+="\n"}};return l}

Prettyfied:

func r(i: Int) -> String {
    var l = "";

    for j in (0 ... i * 2) {
        for k in (0 ..< i * 2 - 1) {
            l += (j == 0 && k < i) ||
            (j > 0 && (j > i ? j - i - 1 : i - j) ... (j > i ? i * 3 - 1 - j : i + j - 2) ~= k) ? "+" : " "
        }

        if j < i * 2 {
            l += "\n"
        }
    }

    return l
}

Try it online!

Tamás Sengel

Posted 2018-04-19T06:57:16.527

Reputation: 211

0

Retina, 35 bytes

¶<,-2`\+
 
\+` (\++)$
$&$%"$1++
^O`

Takes unary + as input

Try it online!

TwiNight

Posted 2018-04-19T06:57:16.527

Reputation: 4 187

0

Jelly, 18 17 14 13 bytes

”+ẋṄ¹Ƥz⁶ŒBṚ;$

Try it online!

-1 byte thanks to Erik the Outgolfer

”+ẋṄ¹Ƥz⁶ŒBṚ;$
”+                  '+' literal
  ẋ                 repeat this <input> number of times: '+++'
   Ṅ                print this string + a new line
    ¹Ƥ              get the prefixes: ['+', '++', '+++']
      z             transpose and fill with...
       ⁶            space (' '). yields ['+++', ' ++', '  +']
        ŒB         palindromize each row: ['+++++', ' +++ ', '  +  ']
          Ṛ;$      reverse and append with itself.

dylnan

Posted 2018-04-19T06:57:16.527

Reputation: 4 993

-> – Erik the Outgolfer – 2018-06-02T11:56:27.333

@EriktheOutgolfer of course, thanks – dylnan – 2018-06-02T15:41:09.847

0

R, 141 139 137 135 126 bytes

Another approach borrowing from the other R answer to this challenge by ngm as well as this other answer from Kirill L.:

function(n)cat(c(g(n),format(sapply(c(1:n,n:1),function(i)g(2*i-1)),j="c",w=2*n-1)),sep="
")
g=function(x)intToUtf8(rep(43,x))

Try it online!

Below a fully recursive solution growing the initial line and the diamond at each step:

function(n)cat("
",intToUtf8(rbind(t(f(n)[c(1:n,n:1),-1]),13)),sep="")
f=function(n)"if"(n,{cat("+");rbind(cbind(32,f(n-1),32),43)},43)

Try it online!

JayCe

Posted 2018-04-19T06:57:16.527

Reputation: 2 655

@Giuseppe Duh! Thanks for pointing it out. – JayCe – 2018-05-16T21:57:03.263

0

CJam, 34 bytes

q~:X,'+X*n{_X-~' *\2*)'+*+}%_W%+:n

Try it online!

Still wrapping my head around CJam, could probably be improved.

maxb

Posted 2018-04-19T06:57:16.527

Reputation: 5 754

0

MY-BASIC, 126 bytes

An anonymous function that takes input as a unary number with + tallys

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

Try it online!

Taylor Scott

Posted 2018-04-19T06:57:16.527

Reputation: 6 709

0

uBASIC, 114 bytes

0input"",s$:n=len(s$):?s$:fork=2ton:t$=t$+" ":nextk:fork=0-nton:f=abs(k):iffthen?mid$(t$+s$+s$,n-f+1,2*n-f)
1nextk

Try it online!

Taylor Scott

Posted 2018-04-19T06:57:16.527

Reputation: 6 709

0

C (gcc), 111 bytes

Rather than having two loops (one for [0..i-1] and [i-i..0]), I loop for 2*i iterations and compute the offsets from 0 for the first half and from 2*i for the last half. printf() takes care of the spacing!

f(i,j,k){char s[9999];for(memset(s,43,j=2*i+1),k=-1;printf("%*.*s\n",i+k,~k?2*k+1:i,s),--j;)k=(j>i)?2*i-j:j-1;}

Try it online!

ErikF

Posted 2018-04-19T06:57:16.527

Reputation: 2 149

Suggest x-~x instead of 2*x+1 and j>i instead of (j>i) – ceilingcat – 2018-08-04T08:15:57.817

0

Oracle SQL, 166 bytes

select decode(x,1,lpad('x',n,'x'),lpad(' ',n-y,' ')||lpad('x',2*y-1,'x'))from(select level x,abs(trunc((level-2)/n)*(2*n+1)+1-level)y,n from t connect by level<2*n+2)

Test in SQL*PLus (This table is used as an input create table t(n) as select 5 from dual)

SQL> set pages 0 lines 2000 feedback off
SQL> select decode(x,1,lpad('x',n,'x'),lpad(' ',n-y,' ')||lpad('x',2*y-1,'x'))
  2  from(select level x,abs(trunc((level-2)/n)*(2*n+1)+1-level)y,n from t connect by level<2*n+2)
  3  /
xxxxx
    x
   xxx
  xxxxx
 xxxxxxx
xxxxxxxxx
xxxxxxxxx
 xxxxxxx
  xxxxx
   xxx
    x

Dr Y Wit

Posted 2018-04-19T06:57:16.527

Reputation: 511

0

C# (Visual C# Interactive Compiler), 105 bytes

n=>new int[2*n+1].Select((_,i)=>new String('+',i<1?n:i>n?4*n-2*i+1:2*i-1).PadLeft(i<1?0:i>n?3*n-i:n+i-1))

Try it online!

The idea is to create an enumerator with length equal to the number of returned lines. Iterate over the enumerator and return strings of + characters with varying padding dependent upon the current index in the enumeration.

// n is the diamond size
n=>
  // create an array to iterate over
  new int[2*n+1]
  // this version of select includes an index
  .Select((_,i)=>
    // create the diamond body
    new String('+',i<1?n:i>n?4*n-2*i+1:2*i-1)
    // pad according
    .PadLeft(i<1?0:i>n?3*n-i:n+i-1))

dana

Posted 2018-04-19T06:57:16.527

Reputation: 2 541