# 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


Answers are scored in characters with fewer characters being better.

• 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. – b_jonas 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
• This here is peak J – Jonah Oct 4 '20 at 14:37

# Clojure, 191 179 bytes

#(loop[[r & s](range 18)h 1](print(apply str(repeat(if(< r 8)(- 8 r)(- r 8))\ )))(doseq[m(concat(range 1 h)(range h 0 -1))](print m))(println)(if s(recur s((if(< r 8)inc dec)h))))


-12 bytes by changing the outer doseq to a loop, which allowed me to get rid of the atom (yay).

A double "for-loop". The outer loop (loop) goes over each row, while the inner loop (doseq) goes over each number in the row, which is in the range (concat (range 1 n) (range n 0 -1)), where n is the highest number in the row.

(defn diamond []
(let [spaces #(apply str (repeat % " "))] ; Shortcut function that produces % many spaces
(loop [[row-n & r-rows] (range 18) ; Deconstruct the row number from the range
high-n 1] ; Keep track of the highest number that should appear in the row
(let [top? (< row-n 8) ; Are we on the top of the diamond?
f (if top? inc dec) ; Decided if we should increment or decrement
n-spaces (if top? (- 8 row-n) (- row-n 8))] ; Calculate how many prefix-spaces to print
(print (spaces n-spaces)) ; Print prefix-spaces
(doseq [m (concat (range 1 high-n) (range high-n 0 -1))] ; Loop over the row of numbers
(print m)) ; Print the number
(println)

(if r-rows
(recur r-rows (f high-n)))))))


Due to a bug in the logic in my first attempt (accidentally inserting the prefix-spaces between each number instead), I managed to get this:

1
1       2       1
1      2      3      2      1
1     2     3     4     3     2     1
1    2    3    4    5    4    3    2    1
1   2   3   4   5   6   5   4   3   2   1
1  2  3  4  5  6  7  6  5  4  3  2  1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
12345678987654321
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
1  2  3  4  5  6  7  8  9  8  7  6  5  4  3  2  1
1   2   3   4   5   6   7   8   7   6   5   4   3   2   1
1    2    3    4    5    6    7    6    5    4    3    2    1
1     2     3     4     5     6     5     4     3     2     1
1      2      3      4      5      4      3      2      1
1       2       3       4       3       2       1
1        2        3        2        1
1         2         1


Not even correct ignoring the obvious bug, but it looked cool.

• That's a super-pretty bug. Perhaps there should be a challenge to generate that... – AJFaraday Jul 5 at 11:37

## 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,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. – John 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 51

Print@@#&/@(Sum[k~DiamondMatrix~17,{k,0,8}]/.0->" ") With 3 bytes saved thanks to Kelly Lowder.

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] /. 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. – chyanog 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

# Python 2, 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
• @gnibbler: This works in Python running on 64-bit platforms, but not on 32-bit platforms. – Konrad Borowski Dec 31 '13 at 8:06

## 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
• @LucasHenrique 307 characters total. i%18-9 is x value on cartesian plane mirroring itself on the y-axis. i/18-8 is y value on cartesian plane mirroring itself on the x-axis. Sum them together to get 1:1 diagonal (which causes numeric shift to form on 1:1 diamond. (32:57)-v is unichar numeric value for ASCII 0-9. 10 new line. – Albert Renshaw Feb 14 '17 at 9:13

# Python 2, 60 59

for n in111111111**2:printint('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. – Konrad Borowski 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

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

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 – chyanog 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. – chyanog Mar 28 '13 at 4:16

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

• damn it!! I missed the space and made half diamond. I must sleep now – Joomler Nov 23 '16 at 12:41

## 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
• I know it's very late, but I always have a need to golf when I see PHP scripts. 83 bytes with <? skipped per meta. Also, you seem to have some encoding problems in the second code. – RedClover May 26 '18 at 18:56
• @Soaku The second one is not mine. It was suggested as an edit to my answer by an anonymous user. I just added it without checking - not really sure why the user didn't just post it as their own attempt really. The meta question post-dates this answer by almost 3 years. – Gareth May 26 '18 at 19:43
• I meant, that I don't include <? in the bytecount. I've made some other improvements too. – RedClover May 26 '18 at 19:58

# 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

• Running this in my browser shows the diamond, but on an additional line a -7 – Christiaan Westerbeek Jul 8 '20 at 22:23

# Vim, 6239 38 keystrokes

Thanks to @DJMcMayhem for saving a ton of bytes!

My first Vim answer, so exciting!

i12345678987654321<ESC>qqYP9|xxI <ESC>YGpHq7@q


I tried to write the numbers via a recording, but it is much longer

Try it online!

### Explanation:

i123 ... 321<ESC>                   Write this in insert mode and enter normal mode
qq                                  Start recording into register q
YP                                Yank this entire line and Paste above
9|                              Go to the 9th column
xx                            Delete character under cursor twice
I <ESC>                     Go to the beginning of the line and insert a space and enter normal mode
Y                    Yank this entire line
G                   Go to the last line
p                  Paste in the line below
H                 Go to the first line
q                End recording
7@q             Repeat this 7 times


EDIT:

I used H instead of gg and saved 1 byte

• You can delete the ma and change ai<space> to I<space>. – DJMcMayhem Dec 4 '16 at 20:20
• Also, you could probably delete stage 3 if you change stage 1 to pasting above and below. – DJMcMayhem Dec 4 '16 at 20:21
• @DJMcMayhem Thank you for the suggestion! I initially was thinking about introducing a new register for the copied bits, but this is much shorter! – user41805 Dec 5 '16 at 8:37

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

## PowerShell (2 options): 9284 45 bytes

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 1s 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. • You can save a byte by casting to a long instead of int64 – Veskah Jul 26 '18 at 20:50 • Another way to save a byte 1..8+9..1|%{' '*(9-$_)+ +($x='1'*$_+'L')*$x} – mazzy Sep 19 '18 at 12:12 # APL (Dyalog Classic), 20 19 bytes (⍉⊢⍪1↓⊖)⍣2⌽↑,⍨\1↓⎕d  Try it online! ⎕d are the digits '0123456789' 1↓ drop the first ('0') ,⍨\ swapped catenate scan, i.e. the reversed prefixes '1' '21' '321' ... '987654321' ↑ mix into a matrix padded with spaces: 1 21 321 ... 987654321  ⌽ reverse the matrix horizontally (...)⍣2 do this twice: ⍉⊢⍪1↓⊖ the transposition (⍉) of the matrix itself (⊢) concatenated vertically (⍪) with the vertically inverted matrix (⊖) without its first row (1↓) # Regenerate, 109 bytes (( {#2-1}| {8})($3${#3+1}|1)(${#4+1}$4|)\n){9}(($6| )(${$7/10}|${$3/10})(${$8-1+1/$8*#7-1/$8}|7){#7-1}\n){8}


Try it here!

## Explanation

The solution is divided into two parts, which generate the upper half of the diamond (including the center line) and the lower half, respectively. The upper half consists of group 1, repeated nine times (...\n){9}; the lower half consists of group 5, repeated eight times (...\n){8}.

The first part of each group handles the spaces. (I've replaced space with underscore in the explanations for better visibility.)

Upper-half spaces:

( {#2-1}| {8})
(            )  Group 2:
_{#2-1}         Space, repeated one less time than the previous length of group 2
|        Or, if this is the first row and there is no previous value of group 2...
_{8}    Space, repeated eight times


Lower-half spaces:

( $6| ) ( ) Group 6: _$6      Space, concatenated to the previous value of group 6
|     Or, if this is the first row and there is no previous value of group 6...
_    A single space


Now for the diamond itself. It can be divided into four quadrants, and I used three different approaches to generate them:

### Top left & top right: concatenation

We generate the left half (including the center) of each row with group 3, and the right half with group 4. For both halves, observe that we can generate the next row by concatenating a digit to the previous row:

 1234 321
|   |
v   v
12345 4321


So we can use a similar approach to what we did for the bottom-half spaces. The only difference is that the character we're concatenating at each step needs to be calculated.

($3${#3+1}|1)
(           )  Group 3:
$3 Previous value of group 3${    }      concatenated to the result of...
#3+1       Previous length of group 3 plus 1
|     Or, if this is the first row and there is no previous value of group 3...
1    The digit 1


(${#4+1}$4|)
(          )  Group 4:
${ } The result of... #4+1 Previous length of group 4 plus 1$4     concatenated to the previous value of group 4
|    Or, if this is the first row and there is no previous value of group 4...
Empty string


### Bottom left: integer division

We generate the left half (including the center) of each row with group 7. Observe that each row is obtained by removing the rightmost digit from the previous row:

12345
|
v
1234


If we treat the entire thing as an integer, we can perform this transformation easily by dividing it by ten:

(${$7/10}|${$3/10})
(                 )  Group 7:
${ } The result of...$7/10              Previous value of group 7, divided by 10
|            Or, if there is no previous value of group 7...
${ } The result of...$3/10     Group 3 (the final upper-left quadrant row) divided by 10


### Bottom right: digit-by-digit

There isn't an easy way to remove a digit from the left side of a previous match, so for the right half of each bottom row, we resort to generating one digit at a time with group 8. Here are the first three rows that we need to generate:

7654321
654321
54321


Each digit is one less than the previous digit, except that we have to "reset" when we hit 1. The reset value is always one less than the length of the left half of the row, which we have access to as group 7.

How can we tell when we've hit 1? I used an integer-division trick I first developed for programming in Acc!!: if N is a positive integer, then 1/N will be one iff N = 1 and zero if N > 1. Multiplying this quantity by (length of group 7) - 1 gives us the reset we need.

(${$8-1+1/$8*#7-1/$8}|7){#7-1}
(                      )        Group 8 (generates one digit at a time):
${ } The result of...$8-1                          Previous value of group 8, minus 1
+     #7                  Plus the length of group 7
1/$8* if the previous value of group 8 equals 1 -1/$8             Minus 1 if the previous value of group 8 equals 1
|           Or, if there is no previous value of group 8...
7          The digit 7
{    }  Generate this many digits on each row:
#7-1   One less than the length of group 7

• This language looks really cool! Funnily enough I was thinking about making a similar one a few weeks back, but figured it'd be too much work :p. Awarding the bounty now. – Redwolf Programs Jun 29 at 15:45

## 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
• @flodel you'd have to note that that prints to stderr, and you could also do for(i in s<-c(1:9,8:1))... to save a byte – Giuseppe Dec 14 '17 at 17:10
• 64 bytes – Giuseppe Apr 6 '18 at 21:05

# k (64 50 chars)

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


Old method:

-1',/(::;1_|:)@\:((|!9)#\:" "),',/'+(::;1_'|:')@\:i#\:,/$i:1+!9;  • (1+!9)#'"1" is ,\9#"1" – ngn Dec 5 '16 at 22:42 # 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)."; + "Add the other rows.";  Lastly, we just join all lines with newlines, with N*. # brainfuck, 158 154 bytes ++++++++[->+>++++>+>++++++<<<<]>>>++<<+[-[-<+>>.<]<[->+<]>>>>+>[->+<<.+>]>+[-<+<.->>]<<<.<<]>>>>-[<<<<+[-<+>>.<]<[->+<]>>>>>[->+<<+.>]>-[-<+<-.>>]<<-<.>>]  Try it online! [spaceMem, spaceCount, space, lf, "0", numCount, numMem] ++++++++[->+>++++>+>++++++<<<<]>>>++<<+ [ for spaceCount -[- for spaceCount minus 1 <+ inc spaceMem >>. print space < go to spaceCount ] <[->+<]> fetch spaceCount from spaceMem >>>+ inc number >[- for numCount >+ inc numMem <<.+ print and inc number > go to numCount ] >+[- for numMem plus 1 <+ inc numCount <.- print and decrement number >> go to numMem ] <<<. print lf << go to spaceCount ] >>>>-[ for numCount <<<<+[- for spaceCount plus 1 <+ inc spaceMem >>. print space < go to spaceCount ] <[->+<]> fetch spaceCount from spaceMem >>> inc number >[- for numCount >+ inc numMem <<+. print and inc number > go to numCount ] >-[- for numMem minus 1 <+ inc numCount <-. print and decrement number >> go to numMem ] <<- decrement number <. print lf >> go to numCount ]  ### Ruby, 76 69 characters f=->x{[*1..x]+[*1...x].reverse};puts f.map{|i|(f[i]*'').center 17}  (Thanks, Patrick!) Improvements welcome. :) • 69 chars: f=->x{[*1..x]+[*1...x].reverse};puts f.map{|i|(f[i]*'').center 17} – Patrick Oscity Nov 5 '12 at 21:11 • Great comment, I didn't know the '...' and didn't understand how this could work. – G B Nov 25 '16 at 7:10 • 60 chars: [*-8..8].map{|i|puts' '*i.abs+"#{eval [?1*(9-i.abs)]*2*?*}"} – G B Nov 25 '16 at 8:05 • 54 chars: (-8..8).map{i=_1.abs;puts' '*i+"#{eval(?1*(9-i))**2}"}. It's the same solution optimized. – Siim Liiser Oct 2 '20 at 12:22 ## 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}%


## 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 • Is +1 for -E standard? I mean perl -E is the same number of characters as perl -e. :) – Mark Reed Aug 23 '20 at 13:58 ## Python, 65 for i in map(int,str(int('1'*9)**2)):print' '*(9-i),int('1'*i)**2  • Try prepending I=int; to your code and replacing all subsequent instances of int with I – Cyoce Nov 27 '16 at 2:51 • @Cyoce I had thought of that. It would save 2 chars each time int is used, and it's used 3 times, so it saves 6 chars at a cost of 6 chars. – cardboard_box Nov 27 '16 at 4:05 # Bash, 126109 87 chars 87: q()(printf %$[9+$1%9]s\\n$[$2*$2];[ 7 -lt $1 ]||(q$[$1+1]${2}1;q $[$1+9] $2)) q 0 1  As it usually goes, changing from iterative to recursive solution helps us win additional bytes. Meaning of parameters to q:$1 How much to remove from 8 to get the number of spaces in the beginning. Note value modulo 9 counts here (actual value is also a hint to quit recursion).

$2 The current chain of 1s to be squared and output by printf. The modus operandi is: 1. output the sequence (ie. if$2 is 11111, output 123454321)
2. (if not yet at 12..9..21 - the recursive step)

2.1. output the next sequence (here: 111111 > $2 , output 12345654321 2.2. output the sequence once again (123454321). In the step 2.2 , we pass (indent value + 9) instead of indent value however, so that the algoritm "knows" we are printing the row for the second time. Without this, the [ 7 -lt$1 ] would be false, causing us to retrigger the recursive step 1. This would never finish then.

The recursion goes like this:

q 0 1:                          1
q 1 11:                       121
q 2 111:                    12321
q 3 1111:                 1234321
q  4 11111:             123454321
q  5 111111:          12345654321
q  6 1111111:       1234567654321
q  7 11111111:    123456787654321
q  8 111111111: 12345678987654321
q 16 11111111:   123456787654321
q 15 1111111:      1234567654321
q 14 111111:         12345654321
q 13 11111:            123454321
q 12 1111:               1234321
q 11 111:                  12321
q 10 11:                     121
q  9 1:                        1


109:

p()(printf "%$[8+i]s\n"$[k*k])
k=;for i in seq 9;do k+=1;p;done;for i in seq 8 -1 1;do k=${k:1};p;done;  "k+=1" is much cheaper as k=$[10*k+1] , and for k being a string of ones it's the same. Same goes for ${k:1} and$[k/10] .

126:

p() (printf "%$[$1+i]s\n" $[k*k];) k=1;for i in seq 8;do p 8;k=$[10*k+1];done;for i in seq 8 -1 0;do p 9;k=$[k/10];done;  I guess there may be even shorter solution, but weather is glorious, I can't stand sitting in front of computer any more :). # Befunge-93, 155 chars 9:v:<,+55<v5*88<v-\9:$_68v
> v>     ^>3p2vpv  -1<!  *
, 1^  2p45*3+9<4:    ,:  +
g -^_75g94+4pg7^!    +^ ,<
1 : ^ 0    :-1$_:68*^$
^1_$:55+\-0\>:#$1-#\$:_^


Try it online!

It could definitely be golfed more, but it's my first Funge program and my head already hurts. Had a lot of fun, though

# JavaScript, 170 bytes

My first code golf :)

## Golfed

a="";function b(c){a+=" ".repeat(10-c);for(i=1;i<c;i++)a+=i;for(i=2;i<c;i++)a+=c-i;a+="\n";}for(i=2;i<11;i++)b(i);for(i=9;i>1;i--)b(i);document.write("<pre>"+a+"</pre>");


## Ungolfed

var str = "";
function row(line) {
str += " ".repeat(10 - line);
for (var i = 1; i < line; i++) {
str += i;
}
for (var i = 2; i < line; i++) {
str += line - i;
}
str += "\n";
}
for (var line = 2; line < 11; line++) {
row(line);
}
for (var line = 9; line > 1; line--) {
row(line);
}
document.write("<pre>" + str + "</pre>");


# Octave, 38 bytes

x=abs(-8:8);m=x+x';m(m>8)=25;[57-m,'']


To make it work in MATLAB too, you'd need to write x=ndgrid(abs(-8:8));m=x+x';m(m>8)=25;[57-m,''] or x=meshgrid(abs(-8:8));m=x+x';m(m>8)=25;[57-m,'']

# Gaia, 9 bytes

9┅…ṫ¦€|ṫṣ


### Explanation

9┅         Push [1 2 3 4 5 6 7 8 9]
…        Prefixes; push [ [1 2] [1 2 3] ... [1 2 3 4 5 6 7 8 9]]
ṫ¦      Palindromize each row: e.g. [1 2 3 4] -> [1 2 3 4 3 2 1]
€|    Centre-align the rows, padding with spaces
ṫ   Palindromize the rows
ṣ  Join with newlines