# Print this diamond

This question has been spreading like a virus in my office. There are quite a variety of approaches:

Print the following:

``````        1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
``````
-
What is the winning criterion ? And is this a challenge or a golf ? – Paul R Oct 12 '12 at 15:33
I read "kolmogorov-complexity" as "code-golf". – DavidC Oct 12 '12 at 16:44
@DavidCarraher "kolmogorov-complexity" was edited in after the question was asked. The original questioner has not specified the winning criteria yet. – Gareth Oct 12 '12 at 20:56
@Gareth My comment was made after the "kolmogorov-complexity" tag was added but before the "code-golf" tag was added. At that time people were still be asking whether it was a code-golf question. – DavidC Oct 12 '12 at 22:00
perlmonks.com/?node_id=891559 has perl solutions. – Zsbán Ambrus Oct 20 '12 at 19:51

## J, 29 26 24 23 22 21 chars

``````,.(0&<#":)"+9-+/~|i:8
``````

Thanks to FUZxxl for the `"+` trick (I don't think I've ever used `u"v` before, heh).

### Explanation

``````                  i:8  "steps" vector: _8 _7 _6 ... _1 0 1 ... 7 8
|     magnitude
+/~      outer product using +
9-         inverts the diamond so that 9 is in the center
(      )"+           for each digit:
#                  copy
0&<                   if positive then 1 else 0
":                copies of the string representation of the digit
(in other words: filter out the strictly positive
,.                     ravel each item of the result of the above
(necessary because the result after `#` turns each
scalar digit into a vector string)
``````
-
Instead of `"0]`, write `"+`. – FUZxxl Apr 11 '15 at 10:26
For one less character, write `,.0(<#":)"+9-+/~|i:8` – FUZxxl Apr 11 '15 at 13:24
Here is your solution translated to 25 characters of APL: `⍪↑{(0<⍵)/⍕⍵}¨9-∘.+⍨|9-⍳17` – FUZxxl Apr 11 '15 at 13:44

## APL (33 31)

``````A⍪1↓⊖A←A,0 1↓⌽A←⌽↑⌽¨⍴∘(1↓⎕D)¨⍳9
``````

If spaces separating the numbers are allowed (as in the Mathematica entry), it can be shortened to 28 26:

``````A⍪1↓⊖A←A,0 1↓⌽A←⌽↑⌽∘⍕∘⍳¨⍳9
``````

Explanation:

• (Long program:)
• `⍳9`: a list of the numbers 1 to 9
• `1↓⎕D`: `⎕D` is the string '0123456789', `1↓` removes the first element
• `⍴∘(1↓⎕D)¨⍳9`: for each element N of `⍳9`, take the first N elements from `1↓⎕D`. This gives a list: ["1", "12", "123", ... "123456789"] as strings
• `⌽¨`: reverse each element of this list. ["1", "21", "321"...]

• (Short program:)

• `⍳¨⍳9`: the list of 1 to N, for N [1..9]. This gives a list [[1], [1,2], [1,2,3] ... [1,2,3,4,5,6,7,8,9]] as numbers.
• `⌽∘⍕∘`: the reverse of string representation of each of these lists. ["1", "2 1"...]
• (The same from now on:)
• `A←⌽↑`: makes a matrix from the list of lists, padding on the right with spaces, and then reverse that. This gives the upper quadrant of the diamond. It is stored in A.
• `A←A,0 1↑⌽A`: A, with the reverse of A minus its first column attached to the right. This gives the upper half of the rectangle. This is then stored in A again.
• `A⍪1↓⊖A`: `⊖A` is A mirrored vertically (giving the lower half), `1↓` removes the top row of the lower half and `A⍪` is the upper half on top of `1↓⊖A`.
-
+1 Amazing. Could you translate it for us APL illiterates? – DavidC Oct 12 '12 at 19:36
Shouldn't non-ascii code be counted in UTF-8 instead of code-points? This would push APL closer to his earthly relatives. – Jan Dvorak Mar 23 '13 at 5:39
@JanDvorak No, since there is an APL code page, which fits the entire character set into a single byte. But I think you've probably figured this out at some point since 2013. ;) – Martin Ender Jan 25 '15 at 0:34

# Mathematica 83 49 43 54

``````Grid[Sum[k~DiamondMatrix~17, {k, 0, 8}] /. 0 -> "", Spacings -> 0]
``````

Analysis

The principal part of the code, `Sum[DiamondMatrix[k, 17], {k, 0, 8}]`, can be checked on WolframAlpha.

The following shows the underlying logic of the approach, on a smaller scale.

``````a = 0~DiamondMatrix~5;
b = 1~DiamondMatrix~5;
c = 2~DiamondMatrix~5;
d = a + b + c;
e = d /. 0 -> "";
Grid /@ {a, b, c, d, e}
``````

-
David, you beat me this time! :-) – Mr.Wizard Oct 21 '12 at 15:29
Another try (55 chars): `f = Table[# - Abs@k, {k, -8, 8}] &; f[f[9]] /. n_ /; n < 1 -> "" // Grid` – DavidC Mar 22 '13 at 17:56
Still another (71 chars): `Table[9 - ManhattanDistance[{9, 10}, {j, k}], {j, 18}, {k, 18}] /. n_ /; n < 1 -> "" // Grid` – DavidC Mar 22 '13 at 17:57
`Grid@#@#@9&[Table[#-Abs@k,{k,-8,8}]&]/.n_/;n<1->""` 50 chars. – chyaong Mar 23 '13 at 4:26
A visual display of the code: `ArrayPlot[Sum[k~DiamondMatrix~17, {k, 0, 8}], AspectRatio -> 2]` – DavidC Nov 23 '13 at 15:53

### GolfScript, 3331 30 characters

Another GolfScript solution

``````17,{8-abs." "*10@-,1>.-1%1>n}%
``````

Thank you to @PeterTaylor for another char.

Previos versions:

``````17,{8-abs" "*9,{)+}/9<.-1%1>+}%n*
``````
``````17,{8-abs" "*9,{)+}/9<.-1%1>n}%
``````
-
You don't need the trailing spaces (the text in the question doesn't have them), so you can skip adding the numbers to the spaces and save one char as `17,{8-abs." "*10@-,1>.-1%1>n}%` – Peter Taylor Mar 28 '13 at 16:21

# Python 726967 61

Not clever:

``````s=str(111111111**2)
for i in map(int,s):print'%8s'%s[:i-1]+s[-i:]
``````
-
doesn't work in Python 3+, which requires parens around the arguments to print :( – Griffin Oct 12 '12 at 18:27
@Griffin: In code golf I choose Python 2 or Python 3 depending on whether I need print to be a function. – Steven Rumbalski Oct 12 '12 at 19:29
`s=`0x2bdc546291f4b1`` – gnibbler Oct 14 '12 at 1:32
@gnibbler. Very clever suggestion. Unfortunately, the repr of that hexadecimal includes a trailing `'L'`. – Steven Rumbalski Oct 15 '12 at 14:51
How about `` s=`111111111**2` ``? It works for me with 2.7.5 - what version are you running? – Daniel Lubarov Nov 19 '13 at 19:37

## C, 79 chars

``````v;main(i){for(;i<307;putchar(i++%18?v>8?32:57-v:10))v=abs(i%18-9)+abs(i/18-8);}
``````
-
Explanation please? – Lucas Henrique Apr 12 '15 at 16:35

# Javascript, 114

My first entry on Codegolf!

``````for(l=n=1;l<18;n-=2*(++l>9)-1,console.log(s+z)){for(x=n,s="";x<9;x++)z=s+=" ";for(x=v=1;x<2*n;v-=2*(++x>n)-1)s+=v}
``````

If this can be shortened any further, please comment :)

-

Mathematica 55 50 45 41 38

``````(10^{9-Abs@Range[-8,8]}-1)^2/81//Grid

Grid[(10^Array[{9}-Abs[#-9]&,17]-1)^2/81]
``````

-
Very nice work. – DavidC Mar 22 '13 at 17:17
@DavidCarraher Thank you :D – chyaong Mar 23 '13 at 4:05
I echo David's remark. How did you come up with this? – Mr.Wizard Mar 27 '13 at 7:02
May I update your answer with the shorter modification I wrote? – Mr.Wizard Mar 27 '13 at 21:49
@Mr.Wizard Certainly. – chyaong Mar 28 '13 at 4:16

## PHP, 92 90 characters

``````<?for(\$a=-8;\$a<9;\$a++){for(\$b=-8;\$b<9;){\$c=abs(\$a)+abs(\$b++);echo\$c>8?" ":9-\$c;}echo"\n";}
``````

Calculates and prints the Manhattan distance of the position from the centre. Prints a space if it's less than 1.

An anonymous user suggested the following improvement (84 characters):

``````<?for(\$a=-8;\$a<9;\$a++,print~õ)for(\$b=-8;\$b<9;print\$c>8?~ß:9-\$c)\$c=abs(\$a)+abs(\$b++);
``````
-
2nd one doesn't work. – Christian Mar 22 '13 at 4:30

# Python, 60 59

``````for n in`111111111**2`:print`int('1'*int(n))**2`.center(17)
``````

Abuses backticks and repunits.

-
The space after `in` keyword can be removed, just like you did with `print` keyboard. – xfix Oct 23 '12 at 17:02
@GlitchMr: Thanks! Updated. – nneonneo Oct 23 '12 at 17:06
I get an extra `L` in the middle seven lines of output. – Steven Rumbalski Mar 28 '13 at 14:56
You shouldn't...what version of Python are you using? – nneonneo Mar 28 '13 at 15:07

### Common Lisp, 113 characters

``````(defun x(n)(if(= n 0)1(+(expt 10 n)(x(1- n)))))(dotimes(n 17)(format t"~17:@<~d~>~%"(expt(x(- 8(abs(- n 8))))2)))
``````

First I noticed that the elements of the diamond could be expressed like so:

``````  1   =   1 ^ 2
121  =  11 ^ 2
12321 = 111 ^ 2
``````

etc.

`x` recursively calculates the base (1, 11, 111, etc), which is squared, and then printed centered by `format`. To make the numbers go up to the highest term and back down again I used `(- 8 (abs (- n 8)))` to avoid a second loop

-

## GolfScript, 36 chars

Assuming that this is meant as a challenge, here's a basic GolfScript solution:

``````9,.);\-1%+:a{a{1\$+7-.0>\" "if}%\;n}%
``````
-

## R, 71 characters

For the records:

``````s=c(1:9,8:1);for(i in s)cat(rep(" ",9-i),s[0:i],s[(i-1):0],"\n",sep="")
``````
-
+1 - can save a few with `message(rep(" ",9-i),s[c(1:i,i:1-1)])` – flodel Apr 11 '15 at 17:14

### Ruby, 76 characters

``````def f(a)a+a.reverse[1..-1]end;puts f [*1..9].map{|i|f([*1..i]*'').center 17}
``````

Improvements welcome. :)

-
69 chars: `f=->x{[*1..x]+[*1...x].reverse};puts f[9].map{|i|(f[i]*'').center 17}` – Patrick Oscity Nov 5 '12 at 21:11

# k (64 50 chars)

``````-1'(::;1_|:)@\:((|!9)#'" "),'\$i*i:"J"\$(1+!9)#'"1";
``````

Old method:

``````-1',/(::;1_|:)@\:((|!9)#\:" "),',/'+(::;1_'|:')@\:i#\:,/\$i:1+!9;
``````

-

# JavaScript, 81

``````for(i=9;--i+9;console.log(s))for(j=9;j;s=j--^9?k>0?k+s+k:" "+s:k+"")k=i<0?j+i:j-i
``````
-

## PowerShell: 9284 45 (2 options)

``````1..8+9..1|%{' '*(9-\$_)+[int64](\$x='1'*\$_)*\$x}
1..9+8..1|%{' '*(9-\$_)+[int64](\$x='1'*\$_)*\$x}
``````

Thanks to Strigoides for the hint to use 1^2,11^2,111^2...

Shaved some characters by:

• Eliminating `\$w`.
• Nested the definition of `\$x` in place of its first use.
• Took some clues from Rynant's solution:
• Combined the integer arrays with `+` instead of `,` which allows elimination of the parenthesis around the arrays and a layer of nesting in the loops.
• Used `9-\$_` to calculate the length of spaces needed, instead of more complicated maths and object methods. This also eliminated the need for `\$y`.

Explanation:

`1..8+9..1` or `1..9+8..1` generates an array of integers ascending from 1 to 9 then descending back to 1.

`|%{`...`}` pipes the integer array into a `ForEach-Object` loop via the built-in alias `%`.

`' '*(9-\$_)+` subtracts the current integer from 9, then creates a string of that many spaces at the start of the output for this line.

`[int64](\$x='1'*\$_)*\$x` defines `\$x` as a string of `1`s as long as the current integer is large. Then it's converted to int64 (required to properly output 1111111112 without using E notation) and squared.

-

## Perl 56 54 characters

Added 1 char for the `-p` switch.

Uses squared repunits to generate the sequence.

``````s//12345678987654321/;s|(.)|\$/.\$"x(9-\$1).(1x\$1)**2|eg
``````
-

# Groovy 77 75

``````i=(-8..9);i.each{a->i.each{c=a.abs()+it.abs();print c>8?' ':9-c};println""}
``````

old version:

``````(-8..9).each{a->(-8..9).each{c=a.abs()+it.abs();print c>8?' ':9-c};println""}
``````
-

### Scala - 86 characters

``````val a="543210/.-./012345";for(i<-a){for(j<-a;k=99-i-j)print(if(k<1)" "else k);println}
``````
-

## Javascript, 137

With recursion:

``````function p(l,n,s){for(i=l;i;s+=" ",i--);for(i=1;i<=n;s+=i++);for(i-=2;i>0;s+=i--);return(s+="\n")+(l?p(l-1,n+1,"")+s:"")}alert(p(8,1,""))
``````

First time on CG :)

### Or 118

If I can find a JS implementation that executes `111111111**2` with higher precision.
(Here: 12345678987654320).

``````a="1",o="\n";for(i=0;i<9;i++,o+="         ".substr(i)+a*a+"\n",a+="1");for(i=8;i;i--)o+=o.split("\n")[i]+"\n";alert(o)
``````
-

## GolfScript (27 chars)

``````17,{8-abs' '*1`9*1\$,>~.*n}/
``````

or

``````17,{8-abs' '*.1`9*+9<~.*n}/
``````

Both work by building a suitable repunit as a string and then converting to int and squaring to get a Demlo number.

-

# CJam, 31 27 bytes

CJam is a lot newer than this challenge, so this answer is not eligible for being accepted. This was a neat little Saturday evening challenge, though. ;)

``````8S*9,:)+9*9/2%{_W%1>+z}2*N*
``````

Test it here.

The idea is to form the upper left quadrant first. Here is how that works:

First, form the string `" 123456789"`, using `8S*9,:)+`. This string is 17 characters long. Now we repeat the string 9 times, and then split it into substrings of length 9 with `9/`. The mismatch between 9 and 17 will offset every other row one character to the left. Printing each substring on its own line we get:

``````        1
23456789
12
3456789
123
456789
1234
56789
12345
6789
123456
789
1234567
89
12345678
9
123456789
``````

So if we just drop every other row (which conveniently works by doing `2%`), we obtain one quadrant as desired:

``````        1
12
123
1234
12345
123456
1234567
12345678
123456789
``````

Finally, we mirror this twice, transposing the grid in between to ensure that the two mirroring operations go along different axes. The mirroring itself is just

``````_      "Duplicate all rows.";
W%    "Reverse their order.";
1>  "Discard the first row (the centre row).";
``````

Lastly, we just join all lines with newlines, with `N*`.

-

# K, 59

``````-1'(-:'9+k,1_|k:!9)\$,/'\$b,1_||:'b:(-1_'a),'|:'a:1_1+!:'!10;
``````
-

## Perl, 43+1

adding +1 for `-E` which is required for `say`

`say\$"x(9-\$_).(1x\$_)**2for 1..9,reverse 1..8`

edit: shortened a bit

-

## Python, 65

``````for i in map(int,str(int('1'*9)**2)):print' '*(9-i),int('1'*i)**2
``````
-

# Perl 6, 42 41 chars

``````say " "x 9-\$_,(1 x\$_)**2 for 1..9,(8...1)
``````

Hey, it's one two characters shorter compared to Perl 5 - Perl 6 needs more whitespace than Perl 5, but it's still shorter.

-

# Javascript - 118 chars

``````for(i=1,s=8,d=0;i>0;d?(i=(i-1)/10,s++):(i=i*10+1,s--)){for(d=d||i>11111111,p='',j=0;j++<=s;)p+=' ';console.log(p+i*i)}
``````

Output:

``````         1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654320
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
``````

Unfortunately, I'm also struggling with Javascripts precision problem with the last calculation of `111111111 * 111111111`

-
There is a bug: The rightmost digit in the center line is 0 in your output. – Thomas W. Nov 19 '12 at 13:40
I know, that is the mentioned precision problem also appearing in Nippeys second solution - do you know a fix for this? – air_blob Nov 19 '12 at 13:53
Oh, sorry, I see. No idea how to fix it--at least nothing that wouldn't make the code significantly larger. – Thomas W. Nov 19 '12 at 14:44
I know, logically this answer is not correct as the output doesn't equal the target output even though its technical implementation should return the correct result. – air_blob Nov 19 '12 at 14:57
See joequncy answer below; codegolf.stackexchange.com/a/8742/7594 – Christian Mar 22 '13 at 4:38

## Javascript 88

``````for(i=9,a=Math.abs;--i>-9;console.log(o))for(j=9,o='';j-->-9;)o+=(n=9-a(i)-a(j))>0?n:' '
``````
-

## Javascript, 129* 126

``````for(i=1;i<18;i++){s="";a=Math.abs(9-i);for(j=0;j<a;j++)s+=" ";for(k=a+1;k<=9;k++)s+=k-a;for(l=8;l>a;l--)s+=l-a;console.log(s)}
``````

Includes suggestion from Shmiddty in comments. Original preserved below:

``````for(i=1;i<18;i++){s="";a=Math.abs(9-i);for(j=0;j<a;j++){s+=" "}for(k=a+1;k<=9;k++){s+=k-a}for(l=8;l>a;l--){s+=l-a}console.log(s)}
``````

I'm sure this could be condensed further, but darned if I know how. :P

-
This gets the JS nod. It multiplies correctly. – Christian Mar 22 '13 at 4:37
Instead of wrapping your for loops in brackets, use a semicolon. eg: `for(j=0;j<a;j++)s+=" ";for(k...` – Shmiddty Mar 22 '13 at 18:59
Thank you for pointing that out, @Shmiddty. I've adjusted the snippet. – joequincy Mar 22 '13 at 21:56