89
\$\begingroup\$

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.

\$\endgroup\$
8
  • 4
    \$\begingroup\$ What is the winning criterion ? And is this a challenge or a golf ? \$\endgroup\$
    – Paul R
    Oct 12 '12 at 15:33
  • 24
    \$\begingroup\$ I read "kolmogorov-complexity" as "code-golf". \$\endgroup\$
    – DavidC
    Oct 12 '12 at 16:44
  • 2
    \$\begingroup\$ @DavidCarraher "kolmogorov-complexity" was edited in after the question was asked. The original questioner has not specified the winning criteria yet. \$\endgroup\$
    – Gareth
    Oct 12 '12 at 20:56
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – DavidC
    Oct 12 '12 at 22:00
  • 3
    \$\begingroup\$ perlmonks.com/?node_id=891559 has perl solutions. \$\endgroup\$
    – b_jonas
    Oct 20 '12 at 19:51

121 Answers 121

1
2 3 4 5
28
\$\begingroup\$

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.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ That's a super-pretty bug. Perhaps there should be a challenge to generate that... \$\endgroup\$
    – AJFaraday
    Jul 5 at 11:37
26
\$\begingroup\$

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
                          digits, implicitly padding with spaces)
,.                     ravel each item of the result of the above
                       (necessary because the result after `#` turns each
                        scalar digit into a vector string)
\$\endgroup\$
4
  • \$\begingroup\$ Instead of "0], write "+. \$\endgroup\$
    – FUZxxl
    Apr 11 '15 at 10:26
  • \$\begingroup\$ For one less character, write ,.0(<#":)"+9-+/~|i:8 \$\endgroup\$
    – FUZxxl
    Apr 11 '15 at 13:24
  • 1
    \$\begingroup\$ Here is your solution translated to 25 characters of APL: ⍪↑{(0<⍵)/⍕⍵}¨9-∘.+⍨|9-⍳17 \$\endgroup\$
    – FUZxxl
    Apr 11 '15 at 13:44
  • \$\begingroup\$ This here is peak J \$\endgroup\$
    – Jonah
    Oct 4 '20 at 14:37
25
\$\begingroup\$

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.
\$\endgroup\$
3
  • 5
    \$\begingroup\$ +1 Amazing. Could you translate it for us APL illiterates? \$\endgroup\$
    – DavidC
    Oct 12 '12 at 19:36
  • 3
    \$\begingroup\$ Shouldn't non-ascii code be counted in UTF-8 instead of code-points? This would push APL closer to his earthly relatives. \$\endgroup\$ Mar 23 '13 at 5:39
  • 5
    \$\begingroup\$ @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. ;) \$\endgroup\$ Jan 25 '15 at 0:34
20
\$\begingroup\$

Mathematica 83 49 43 54 51

Print@@#&/@(Sum[k~DiamondMatrix~17,{k,0,8}]/.0->" ")

formatting improved


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}

grids

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

Python 2, 72 69 67 61

Not clever:

s=str(111111111**2)
for i in map(int,s):print'%8s'%s[:i-1]+s[-i:]
\$\endgroup\$
6
  • 2
    \$\begingroup\$ doesn't work in Python 3+, which requires parens around the arguments to print :( \$\endgroup\$
    – Griffin
    Oct 12 '12 at 18:27
  • 9
    \$\begingroup\$ @Griffin: In code golf I choose Python 2 or Python 3 depending on whether I need print to be a function. \$\endgroup\$ Oct 12 '12 at 19:29
  • 5
    \$\begingroup\$ s=`0x2bdc546291f4b1` \$\endgroup\$
    – gnibbler
    Oct 14 '12 at 1:32
  • 1
    \$\begingroup\$ @gnibbler. Very clever suggestion. Unfortunately, the repr of that hexadecimal includes a trailing 'L'. \$\endgroup\$ Oct 15 '12 at 14:51
  • 1
    \$\begingroup\$ @gnibbler: This works in Python running on 64-bit platforms, but not on 32-bit platforms. \$\endgroup\$ Dec 31 '13 at 8:06
15
\$\begingroup\$

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);}
\$\endgroup\$
2
  • 4
    \$\begingroup\$ Explanation please? \$\endgroup\$ Apr 12 '15 at 16:35
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Feb 14 '17 at 9:13
14
\$\begingroup\$

Python 2, 60 59

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

Abuses backticks and repunits.

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

GolfScript, 33 31 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*

(run online)

17,{8-abs" "*9,{)+}/9<.-1%1>n}%
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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}% \$\endgroup\$ Mar 28 '13 at 16:21
12
\$\begingroup\$

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]

Mathematica graphics

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

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

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

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++);
\$\endgroup\$
4
  • \$\begingroup\$ 2nd one doesn't work. \$\endgroup\$
    – Christian
    Mar 22 '13 at 4:30
  • \$\begingroup\$ 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. \$\endgroup\$
    – RedClover
    May 26 '18 at 18:56
  • \$\begingroup\$ @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. \$\endgroup\$
    – Gareth
    May 26 '18 at 19:43
  • \$\begingroup\$ I meant, that I don't include <? in the bytecount. I've made some other improvements too. \$\endgroup\$
    – RedClover
    May 26 '18 at 19:58
8
\$\begingroup\$

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

\$\endgroup\$
8
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Running this in my browser shows the diamond, but on an additional line a -7 \$\endgroup\$ Jul 8 '20 at 22:23
8
\$\begingroup\$

Charcoal, 13 bytes

F⁹«GX⁻⁹ιI⁺ι¹↓

Try it online!

How?

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

F⁹«   Loop ι from 0 to 8:
GX     Draw a (filled) polygon with four equilateral diagonal sides
⁻⁹ι      of length 9-ι
I⁺ι¹    using str(ι+1) as the character
↓       Move down one space before drawing the next one
\$\endgroup\$
1
  • 5
    \$\begingroup\$ This should be now competing as per new consensus in meta. \$\endgroup\$ Sep 13 '17 at 8:16
8
\$\begingroup\$

Vim, 62 39 38 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
\$\endgroup\$
5
  • \$\begingroup\$ You can delete the ma and change `ai<space> to I<space>. \$\endgroup\$
    – DJMcMayhem
    Dec 4 '16 at 20:20
  • \$\begingroup\$ Also, you could probably delete stage 3 if you change stage 1 to pasting above and below. \$\endgroup\$
    – DJMcMayhem
    Dec 4 '16 at 20:21
  • \$\begingroup\$ @DJMcMayhem Thank you for the suggestion! I initially was thinking about introducing a new register for the copied bits, but this is much shorter! \$\endgroup\$
    – user41805
    Dec 5 '16 at 8:37
  • \$\begingroup\$ 34 bytes by generating the 12345678987654321 mathematically. Readable version \$\endgroup\$ Sep 7 at 20:56
  • \$\begingroup\$ @AaronMiller Thanks, updated. \$\endgroup\$
    – user41805
    Sep 9 at 8:10
6
\$\begingroup\$

PowerShell (2 options): 92 84 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.

enter image description here

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You can save a byte by casting to a long instead of int64 \$\endgroup\$
    – Veskah
    Jul 26 '18 at 20:50
  • \$\begingroup\$ Another way to save a byte 1..8+9..1|%{' '*(9-$_)+ +($x='1'*$_+'L')*$x} \$\endgroup\$
    – mazzy
    Sep 19 '18 at 12:12
6
\$\begingroup\$

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

\$\endgroup\$
5
\$\begingroup\$

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
]
\$\endgroup\$
5
+150
\$\begingroup\$

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.

Top left quadrant:

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

Top right quadrant:

(${#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
\$\endgroup\$
1
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Jun 29 at 15:45
5
\$\begingroup\$

Ruby, 76 69 60 54 characters

(-8..8).map{i=_1.abs;puts' '*i+"#{eval(?1*(9-i))**2}"}

(Thanks, Patrick, G B, and Slim Liser!)

Improvements welcome. :)

\$\endgroup\$
4
  • 2
    \$\begingroup\$ 69 chars: f=->x{[*1..x]+[*1...x].reverse};puts f[9].map{|i|(f[i]*'').center 17} \$\endgroup\$ Nov 5 '12 at 21:11
  • \$\begingroup\$ Great comment, I didn't know the '...' and didn't understand how this could work. \$\endgroup\$
    – G B
    Nov 25 '16 at 7:10
  • \$\begingroup\$ 60 chars: [*-8..8].map{|i|puts' '*i.abs+"#{eval [?1*(9-i.abs)]*2*?*}"} \$\endgroup\$
    – G B
    Nov 25 '16 at 8:05
  • 1
    \$\begingroup\$ 54 chars: (-8..8).map{i=_1.abs;puts' '*i+"#{eval(?1*(9-i))**2}"}. It's the same solution optimized. \$\endgroup\$ Oct 2 '20 at 12:22
4
\$\begingroup\$

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="")
\$\endgroup\$
3
  • \$\begingroup\$ +1 - can save a few with message(rep(" ",9-i),s[c(1:i,i:1-1)]) \$\endgroup\$
    – flodel
    Apr 11 '15 at 17:14
  • \$\begingroup\$ @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 \$\endgroup\$
    – Giuseppe
    Dec 14 '17 at 17:10
  • 1
    \$\begingroup\$ 64 bytes \$\endgroup\$
    – Giuseppe
    Apr 6 '18 at 21:05
4
\$\begingroup\$

k (64 50 chars)

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

Old method:

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

\$\endgroup\$
1
  • \$\begingroup\$ (1+!9)#'"1" is ,\9#"1" \$\endgroup\$
    – ngn
    Dec 5 '16 at 22:42
4
\$\begingroup\$

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*.

\$\endgroup\$
4
\$\begingroup\$

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!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Feb 26 at 0:00
4
\$\begingroup\$

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.

\$\endgroup\$
4
+50
\$\begingroup\$

jq -rn, 76 65 60 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:
r |            Start with the results of r
[              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
add            concatenate it together

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.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ tostring can be shortened to @sh here. In general @text and "\(.)" are equivalent with tostring. \$\endgroup\$
    – ovs
    Sep 4 at 21:08
  • \$\begingroup\$ And join("") can be shortened to add. \$\endgroup\$ Sep 4 at 21:29
  • \$\begingroup\$ @ovs Very nice! I seem to have skipped over the @ functions when I was looking through the docs. \$\endgroup\$
    – DLosc
    Sep 7 at 15:06
  • \$\begingroup\$ Applying this tip by ovs you can go down to 60 bytes. \$\endgroup\$ Sep 7 at 16:22
  • 1
    \$\begingroup\$ @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! \$\endgroup\$
    – DLosc
    Sep 7 at 19:41
4
\$\begingroup\$

Raku, 42 41 38 35 chars

say " "x 9-$_,(1 x$_)²for 1…9…1

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ @FrownyFrog Something did change in Perl 6 since this was written (this is a very old answer), fixed. \$\endgroup\$ Jul 27 '18 at 12:42
3
\$\begingroup\$

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}%
\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ Is +1 for -E standard? I mean perl -E is the same number of characters as perl -e. :) \$\endgroup\$
    – Mark Reed
    Aug 23 '20 at 13:58
3
\$\begingroup\$

Python, 65

for i in map(int,str(int('1'*9)**2)):print' '*(9-i),int('1'*i)**2
\$\endgroup\$
2
  • \$\begingroup\$ Try prepending I=int; to your code and replacing all subsequent instances of int with I \$\endgroup\$
    – Cyoce
    Nov 27 '16 at 2:51
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Nov 27 '16 at 4:05
1
2 3 4 5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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