# 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 ? Oct 12, 2012 at 15:33
• I read "kolmogorov-complexity" as "code-golf". Oct 12, 2012 at 16:44
• @DavidCarraher "kolmogorov-complexity" was edited in after the question was asked. The original questioner has not specified the winning criteria yet. Oct 12, 2012 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. Oct 12, 2012 at 22:00
• perlmonks.com/?node_id=891559 has perl solutions. Oct 20, 2012 at 19:51

# 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... Jul 5, 2021 at 11:37
• the bugged output also incorrectly contains a 10. Jul 22, 2023 at 7:37

## 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 "+. Apr 11, 2015 at 10:26
• For one less character, write ,.0(<#":)"+9-+/~|i:8 Apr 11, 2015 at 13:24
• Here is your solution translated to 25 characters of APL: ⍪↑{(0<⍵)/⍕⍵}¨9-∘.+⍨|9-⍳17 Apr 11, 2015 at 13:44
• This here is peak J Oct 4, 2020 at 14: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], [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? Oct 12, 2012 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. Mar 23, 2013 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. ;) Jan 25, 2015 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! :-) Oct 21, 2012 at 15:29
• Another try (55 chars): f = Table[# - Abs@k, {k, -8, 8}] &; f[f[9]] /. n_ /; n < 1 -> "" // Grid Mar 22, 2013 at 17:56
• Still another (71 chars): Table[9 - ManhattanDistance[{9, 10}, {j, k}], {j, 18}, {k, 18}] /. n_ /; n < 1 -> "" // Grid Mar 22, 2013 at 17:57
• Grid@#@#@9&[Table[#-Abs@k,{k,-8,8}]&]/.n_/;n<1->"" 50 chars. Mar 23, 2013 at 4:26
• A visual display of the code: ArrayPlot[Sum[k~DiamondMatrix~17, {k, 0, 8}], AspectRatio -> 2] Nov 23, 2013 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 :( Oct 12, 2012 at 18:27
• @Griffin: In code golf I choose Python 2 or Python 3 depending on whether I need print to be a function. Oct 12, 2012 at 19:29
• s=0x2bdc546291f4b1 Oct 14, 2012 at 1:32
• @gnibbler. Very clever suggestion. Unfortunately, the repr of that hexadecimal includes a trailing 'L'. Oct 15, 2012 at 14:51
• @gnibbler: This works in Python running on 64-bit platforms, but not on 32-bit platforms.
– null
Dec 31, 2013 at 8:06

# C (gcc), 79 bytes

v;main(i){for(;i<307;putchar(i++%18?v>8?32:57-v:10))v=abs(i%18-9)+abs(i/18-8);}


Try it online!

• Explanation please? Apr 12, 2015 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. Feb 14, 2017 at 9:13

# Python 2, 60 59 bytes

for n in111111111**2:printint('1'*int(n))**2.center(17)


Try it online!

Abuses backticks and repunits.

• The space after in keyword can be removed, just like you did with print keyboard.
– null
Oct 23, 2012 at 17:02
• I get an extra L in the middle seven lines of output. Mar 28, 2013 at 14:56
• You shouldn't...what version of Python are you using? Mar 28, 2013 at 15:07

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. Mar 22, 2013 at 17:17
• I echo David's remark. How did you come up with this? Mar 27, 2013 at 7:02
• May I update your answer with the shorter modification I wrote? Mar 27, 2013 at 21:49
• @Mr.Wizard Certainly. Mar 28, 2013 at 4:16
• For the record: The  is the Transpose operator (put it in Mathematica) Feb 28, 2016 at 4:57

# 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 Nov 23, 2016 at 12:41

# GolfScript, 3331 30 bytes

Another GolfScript solution

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


Try it online!

Thank you to @PeterTaylor for another char.

Previous versions:

17,{8-abs" "*9,{)+}/9<.-1%1>+}%n*


Try it online!

17,{8-abs" "*9,{)+}/9<.-1%1>n}%


Try it online!

• 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}% Mar 28, 2013 at 16:21

# Vim, 623938 34 keystrokes

Thanks to @DJMcMayhem for saving a ton of bytes

Thanks to @AaronMiller for saving 4 bytes by generating 12345678987654321 in a different way

9i1<ESC>|C<C-r>=<C-r>"*<C-r>"
<ESC>qqYP9|xxI <ESC>YGpHq7@q


Try it online!

### Explanation:

9i1<ESC>                            Write 9 '1's, leaving the cursor at the end of the line
|C                          Go to the first column and cut all that's to the right of the cursor (implictly into register "), entering insert mode
<C-r>=                    Enter an expression:
<C-r>"*<C-r>"        The contents of register " multiplied with itself
<CR>   Evaluate it, yielding 12345678987654321

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

• You can delete the ma and change ai<space> to I<space>. Dec 4, 2016 at 20:20
• Also, you could probably delete stage 3 if you change stage 1 to pasting above and below. Dec 4, 2016 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! Dec 5, 2016 at 8:37
• 34 bytes by generating the 12345678987654321 mathematically. Readable version Sep 7, 2021 at 20:56
• @AaronMiller Thanks, updated. Sep 9, 2021 at 8:10

## 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. Mar 22, 2013 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. May 26, 2018 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. May 26, 2018 at 19:43
• I meant, that I don't include <? in the bytecount. I've made some other improvements too. May 26, 2018 at 19:58
• Very late to the party too, but you can replace "\n" by " " (double quotes with litterally a new line inside, doesn't work in comments) Jul 24, 2023 at 17:35

# Charcoal, 13 bytes

Ｆ⁹«ＧX⁻⁹ιＩ⁺ι¹↓


Try it online!

### How?

Draws nine, successively smaller, concentric number-diamonds on top of each other:

Ｆ⁹«   Loop ι from 0 to 8:
ＧX     Draw a (filled) polygon with four equilateral diagonal sides
⁻⁹ι      of length 9-ι
Ｉ⁺ι¹    using str(ι+1) as the character
↓       Move down one space before drawing the next one

• This should be now competing as per new consensus in meta. Sep 13, 2017 at 8:16

# JavaScript (V8), 81 bytes

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


Try it online!

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

# Common Lisp, 113 bytes

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


Try it online!

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

# Regenerate, 109 108 bytes

(( {#2-1}| {8})($3${#3+1}|1)(${#4+1}$4|)\n){9}(( $6| )(${$7/10}|${$3/10})(${$8-1+1/$8*(#7-1)}|7){#7-1}\n){8}


Attempt This Online!

## 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)}|7){#7-1} ( ) Group 8 (generates one digit at a time):${                }            The result of...
$8-1 Previous value of group 8, minus 1 + Plus #7-1 The length of group 7 minus 1 1/$8*(    )             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. Jun 29, 2021 at 15:45

# Uiua, 17 bytes

+@!÷⊃≥+8⊞+.↧⇌.⇡17


We use ⇡17 to make a range from 0 to 16, and then min it by its reverse ↧⇌. to get

[0 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 0]


Then ⊞+. makes an addition table of this list with itself:

╭─
╷ 0 1  2  3  4  5  6  7  8  7  6  5  4  3  2 1 0
1 2  3  4  5  6  7  8  9  8  7  6  5  4  3 2 1
2 3  4  5  6  7  8  9 10  9  8  7  6  5  4 3 2
3 4  5  6  7  8  9 10 11 10  9  8  7  6  5 4 3
4 5  6  7  8  9 10 11 12 11 10  9  8  7  6 5 4
5 6  7  8  9 10 11 12 13 12 11 10  9  8  7 6 5
6 7  8  9 10 11 12 13 14 13 12 11 10  9  8 7 6
7 8  9 10 11 12 13 14 15 14 13 12 11 10  9 8 7
8 9 10 11 12 13 14 15 16 15 14 13 12 11 10 9 8
7 8  9 10 11 12 13 14 15 14 13 12 11 10  9 8 7
6 7  8  9 10 11 12 13 14 13 12 11 10  9  8 7 6
5 6  7  8  9 10 11 12 13 12 11 10  9  8  7 6 5
4 5  6  7  8  9 10 11 12 11 10  9  8  7  6 5 4
3 4  5  6  7  8  9 10 11 10  9  8  7  6  5 4 3
2 3  4  5  6  7  8  9 10  9  8  7  6  5  4 3 2
1 2  3  4  5  6  7  8  9  8  7  6  5  4  3 2 1
0 1  2  3  4  5  6  7  8  7  6  5  4  3  2 1 0
╯


Now we do something clever. Let's call this array x. Then ⊃≥+8 pushes +8x and ≥8x, and ÷ divides the two.

╭─
╷ ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  16 ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞
∞  ∞  ∞  ∞  ∞  ∞  ∞  16 17 16 ∞  ∞  ∞  ∞  ∞  ∞  ∞
∞  ∞  ∞  ∞  ∞  ∞  16 17 18 17 16 ∞  ∞  ∞  ∞  ∞  ∞
∞  ∞  ∞  ∞  ∞  16 17 18 19 18 17 16 ∞  ∞  ∞  ∞  ∞
∞  ∞  ∞  ∞  16 17 18 19 20 19 18 17 16 ∞  ∞  ∞  ∞
∞  ∞  ∞  16 17 18 19 20 21 20 19 18 17 16 ∞  ∞  ∞
∞  ∞  16 17 18 19 20 21 22 21 20 19 18 17 16 ∞  ∞
∞  16 17 18 19 20 21 22 23 22 21 20 19 18 17 16 ∞
16 17 18 19 20 21 22 23 24 23 22 21 20 19 18 17 16
∞  16 17 18 19 20 21 22 23 22 21 20 19 18 17 16 ∞
∞  ∞  16 17 18 19 20 21 22 21 20 19 18 17 16 ∞  ∞
∞  ∞  ∞  16 17 18 19 20 21 20 19 18 17 16 ∞  ∞  ∞
∞  ∞  ∞  ∞  16 17 18 19 20 19 18 17 16 ∞  ∞  ∞  ∞
∞  ∞  ∞  ∞  ∞  16 17 18 19 18 17 16 ∞  ∞  ∞  ∞  ∞
∞  ∞  ∞  ∞  ∞  ∞  16 17 18 17 16 ∞  ∞  ∞  ∞  ∞  ∞
∞  ∞  ∞  ∞  ∞  ∞  ∞  16 17 16 ∞  ∞  ∞  ∞  ∞  ∞  ∞
∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞  16 ∞  ∞  ∞  ∞  ∞  ∞  ∞  ∞
╯


And now +@! adds these as offsets to the char ! (ASCII 33), which maps 16…24 to ASCII digits 19 but miraculously treats ∞ as -1 to produce a space (ASCII 32).

╭─
╷ "        1        "
"       121       "
"      12321      "
"     1234321     "
"    123454321    "
"   12345654321   "
"  1234567654321  "
" 123456787654321 "
"12345678987654321"
" 123456787654321 "
"  1234567654321  "
"   12345654321   "
"    123454321    "
"     1234321     "
"      12321      "
"       121       "
"        1        "
╯


## 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 Jul 26, 2018 at 20:50 • Another way to save a byte 1..8+9..1|%{' '*(9-$_)+ +($x='1'*$_+'L')*$x} Sep 19, 2018 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↓) • This doesn't work for me in Dyalog? The ,⍨\1↓⎕d looks right, but adding the mix ↑ just results in 1. If I enclose before mixing, I get something closer, but it's still printed all on one line... Mar 6 at 2:26 • @MarkReed what's your ⎕ml? – ngn Mar 6 at 9:55 • My comment disappeared and I thought it hadn't gone through, or I would have deleted it. Sorry! I thought I had tried different ⎕ml values, but it seems that my first attempt was under ⎕ml = 3; it works under lower levels. Mar 6 at 19:02 • Well, it works under ⎕ml = 1; it also fails under ⎕ml = 2. Mar 6 at 19:08 ### Ruby, 766960 54 characters (-8..8).map{i=_1.abs;puts' '*i+"#{eval(?1*(9-i))**2}"}  (Thanks, Patrick, G B, and Slim Liser!) Improvements welcome. :) • 69 chars: f=->x{[*1..x]+[*1...x].reverse};puts f[9].map{|i|(f[i]*'').center 17} Nov 5, 2012 at 21:11 • Great comment, I didn't know the '...' and didn't understand how this could work. – G B Nov 25, 2016 at 7:10 • 60 chars: [*-8..8].map{|i|puts' '*i.abs+"#{eval [?1*(9-i.abs)]*2*?*}"} – G B Nov 25, 2016 at 8:05 • 54 chars: (-8..8).map{i=_1.abs;puts' '*i+"#{eval(?1*(9-i))**2}"}. It's the same solution optimized. Oct 2, 2020 at 12:22 # 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 ]  # Python 3, 54 bytes saved another 3 bytes by letting the int function crash instead of a loop condition. Thanks to dingledooper. i=8 while[print(f'{int("1"*(9-abs(i)))**2:^17}')]:i-=1  Try it online! Python 3, 57 bytes saved 1 byte by using f-Strings thanks to dingledooper. i=8 while i+9:print(f'{int("1"*(9-abs(i)))**2:^17}');i-=1  Try it online! Python 3, 58 bytes Even shorter solution by a different approach (prints one extra space at the beginning of each line). i=8 while i+9:j=abs(i);i-=1;print(' '*j,int('1'*(9-j))**2)  Try it online! Python 3, 61 bytes (without extra spaces) i=8 while i+9:j=9-abs(i);i-=1;print(f'%{8+j}d'%int('1'*j)**2)  Try it online! These are my previous solutions: Python 3, 66 bytes f=lambda c:f'%{8+c}d'%int('1'*c)**2 for c in f(9):print(f(int(c)))  Try it online! Python 3, 71 bytes: f=lambda c:str(int('1'*int(c))**2) for c in f(9):print(f(c).center(17))  Try it online! • Here's 57 bytes using f-strings. In addition, there's this magical 54 byte solution which works because int() throws an error on an empty string. Feb 26, 2021 at 0:00 # Raku, 424138 35 chars say " "x 9-$_,(1 x$_)²for 1…9…1  Try it online! • @FrownyFrog Something did change in Perl 6 since this was written (this is a very old answer), fixed. – null Jul 27, 2018 at 12:42 # JavaScript (V8), 67 bytes z="9" for(z of(s=n=>n<z?n+s(n+1)+n:z)(1))print("".padEnd(9-z)+s(1))  One byte less thanks to Fhuvi Try it online! ### JavaScript (V8), 68 bytes s=n=>n<z?n+s(n+1)+n:z z="9" for(z of s(1))print("".padEnd(9-z)+s(1))  Try it online! • You can gain 1 byte by declaring the recursive function the first time you use it (because it allows to get rid of the space after the of) : Try it online! FIY, since your code is the shortest JS answer for this challenge, i took the liberty to re-use it for another challenge :) codegolf.stackexchange.com/a/263329/116582 Jul 28, 2023 at 8:58 # 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, 2016 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).";


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

# jq -nr, 55 bytes

range(17)-8|fabs|" "*.+"123456789"[:9-.]+"87654321"[.:]


fabs is not supported on TIO but you can try it on https://jqplay.org/.

Alternatively try it on TIO with .*.|sqrt instead of fabs, for 59 bytes.

# jq-rn, 766560 59 bytes

-6 bytes thanks to ovs and another -6 (plus -5 more indirectly) thanks to Michael Chatiskatzi

def r:range(9),7-range(8);r|[8-.-r|"\(" "*.//1-.)"[:1]]|add


Try it online!

### Explanation

The -n flag specifies that there is no input; the -r flag outputs the result strings, each on its own line, without quotes.

def r:         Define a helper function r
range(9),      which generates the numbers 0 through 8, followed by
7 - range(8);  the numbers 7 through 0
Main program:
[              For each of those numbers, put the following in a list:
8 - . - r |    8, minus the current number, minus the results of calling r again
"\(            For each of those numbers, interpolate the following into a string:
" " * .        Try to repeat a space that many times
//             and if the result is null (i.e. the number was less than 1),
1 - .          subtract the number from 1 instead
)"
[:1]           Take the first character of each resulting string
] |            Take each resulting list of strings and


To help visualize what's going on, here's what just the r|[8-.-r] part does:

[8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8]
[7,6,5,4,3,2,1,0,-1,0,1,2,3,4,5,6,7]
[6,5,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6]
[5,4,3,2,1,0,-1,-2,-3,-2,-1,0,1,2,3,4,5]
[4,3,2,1,0,-1,-2,-3,-4,-3,-2,-1,0,1,2,3,4]
[3,2,1,0,-1,-2,-3,-4,-5,-4,-3,-2,-1,0,1,2,3]
[2,1,0,-1,-2,-3,-4,-5,-6,-5,-4,-3,-2,-1,0,1,2]
[1,0,-1,-2,-3,-4,-5,-6,-7,-6,-5,-4,-3,-2,-1,0,1]
[0,-1,-2,-3,-4,-5,-6,-7,-8,-7,-6,-5,-4,-3,-2,-1,0]
[1,0,-1,-2,-3,-4,-5,-6,-7,-6,-5,-4,-3,-2,-1,0,1]
[2,1,0,-1,-2,-3,-4,-5,-6,-5,-4,-3,-2,-1,0,1,2]
[3,2,1,0,-1,-2,-3,-4,-5,-4,-3,-2,-1,0,1,2,3]
[4,3,2,1,0,-1,-2,-3,-4,-3,-2,-1,0,1,2,3,4]
[5,4,3,2,1,0,-1,-2,-3,-2,-1,0,1,2,3,4,5]
[6,5,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6]
[7,6,5,4,3,2,1,0,-1,0,1,2,3,4,5,6,7]
[8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8]


Any number that's greater than 0 gets turned into that many spaces (and then trimmed back to a single space). The other numbers gets subtracted from 1 (turning 0 .. -8 into 1 .. 9) and stringified.

• tostring can be shortened to @sh here. In general @text and "\(.)" are equivalent with tostring.
– ovs
Sep 4, 2021 at 21:08
• And join("") can be shortened to add. Sep 4, 2021 at 21:29
• @ovs Very nice! I seem to have skipped over the @ functions when I was looking through the docs. Sep 7, 2021 at 15:06
• Applying this tip by ovs you can go down to 60 bytes. Sep 7, 2021 at 16:22
• @MichaelChatiskatzi Wow, that's a weird idiom. After some playing around, I found a different 60-byte solution that only uses //, which I like better, but thanks for inspiring me to look! Sep 7, 2021 at 19:41

# R, 71 bytes

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


Try it online!

• +1 - can save a few with message(rep(" ",9-i),s[c(1:i,i:1-1)]) Apr 11, 2015 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 Dec 14, 2017 at 17:10
• 64 bytes Apr 6, 2018 at 21:05

## 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`. :) Aug 23, 2020 at 13:58