Print this diamond

77

15

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.

Eric Wilson

Posted 2012-10-12T14:43:14.583

Reputation: 879

If you drop by PPCG again some time, I think you should update the accepted answer to the one in J. – Martin Ender – 2015-01-25T00:35:00.067

@MartinBüttner not following you here. Not sure which answer you seem correct. – Eric Wilson – 2015-01-26T01:06:41.207

@EricWilson As far as I can tell, this is the shortest answer.

– Martin Ender – 2015-01-26T08:05:33.403

4What is the winning criterion ? And is this a challenge or a golf ? – Paul R – 2012-10-12T15:33:45.947

21I read "kolmogorov-complexity" as "code-golf". – DavidC – 2012-10-12T16:44:20.260

1@DavidCarraher "kolmogorov-complexity" was edited in after the question was asked. The original questioner has not specified the winning criteria yet. – Gareth – 2012-10-12T20:56:24.227

@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 – 2012-10-12T22:00:28.373

3http://www.perlmonks.com/?node_id=891559 has perl solutions. – b_jonas – 2012-10-20T19:51:10.663

Answers

24

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)

FireFly

Posted 2012-10-12T14:43:14.583

Reputation: 7 107

Instead of "0], write "+. – FUZxxl – 2015-04-11T10:26:47.057

For one less character, write ,.0(<#":)"+9-+/~|i:8 – FUZxxl – 2015-04-11T13:24:20.980

1Here is your solution translated to 25 characters of APL: ⍪↑{(0<⍵)/⍕⍵}¨9-∘.+⍨|9-⍳17 – FUZxxl – 2015-04-11T13:44:06.093

25

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.

marinus

Posted 2012-10-12T14:43:14.583

Reputation: 30 224

5

@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 – 2015-01-25T00:34:02.270

5+1 Amazing. Could you translate it for us APL illiterates? – DavidC – 2012-10-12T19:36:36.020

3Shouldn't non-ascii code be counted in UTF-8 instead of code-points? This would push APL closer to his earthly relatives. – John Dvorak – 2013-03-23T05:39:08.927

23

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.

Carcigenicate

Posted 2012-10-12T14:43:14.583

Reputation: 3 295

20

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

DavidC

Posted 2012-10-12T14:43:14.583

Reputation: 24 524

1David, you beat me this time! :-) – Mr.Wizard – 2012-10-21T15:29:20.650

1Another try (55 chars): f = Table[# - Abs@k, {k, -8, 8}] &; f[f[9]] /. n_ /; n < 1 -> "" // Grid – DavidC – 2013-03-22T17:56:51.583

Still another (71 chars): Table[9 - ManhattanDistance[{9, 10}, {j, k}], {j, 18}, {k, 18}] /. n_ /; n < 1 -> "" // Grid – DavidC – 2013-03-22T17:57:31.117

2Grid@#@#@9&[Table[#-Abs@k,{k,-8,8}]&]/.n_/;n<1->"" 50 chars. – chyanog – 2013-03-23T04:26:23.573

Print@@#&/@(Sum[k~DiamondMatrix~17,{k,0,8}]/. 0->" ") is 3 characters shorter and preserves the lack of spacing between characters – Kelly Lowder – 2016-11-25T15:38:54.537

@Kelly, Yes, thanks. – DavidC – 2016-11-25T19:15:04.207

A visual display of the code: ArrayPlot[Sum[k~DiamondMatrix~17, {k, 0, 8}], AspectRatio -> 2] – DavidC – 2013-11-23T15:53:46.157

15

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

Steven Rumbalski

Posted 2012-10-12T14:43:14.583

Reputation: 1 353

1doesn't work in Python 3+, which requires parens around the arguments to print :( – Griffin – 2012-10-12T18:27:00.847

7@Griffin: In code golf I choose Python 2 or Python 3 depending on whether I need print to be a function. – Steven Rumbalski – 2012-10-12T19:29:09.563

3s=\0x2bdc546291f4b1`` – gnibbler – 2012-10-14T01:32:54.617

1@gnibbler. Very clever suggestion. Unfortunately, the repr of that hexadecimal includes a trailing 'L'. – Steven Rumbalski – 2012-10-15T14:51:11.817

How about s=`111111111**2`? It works for me with 2.7.5 - what version are you running? – Daniel Lubarov – 2013-11-19T19:37:27.940

1@gnibbler: This works in Python running on 64-bit platforms, but not on 32-bit platforms. – Konrad Borowski – 2013-12-31T08:06:33.240

14

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

baby-rabbit

Posted 2012-10-12T14:43:14.583

Reputation: 1 623

4Explanation please? – Lucas Henrique – 2015-04-12T16:35:06.390

1@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 – 2017-02-14T09:13:02.497

14

Python 2, 60 59

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

Abuses backticks and repunits.

nneonneo

Posted 2012-10-12T14:43:14.583

Reputation: 11 445

The space after in keyword can be removed, just like you did with print keyboard. – Konrad Borowski – 2012-10-23T17:02:05.863

@GlitchMr: Thanks! Updated. – nneonneo – 2012-10-23T17:06:20.083

I get an extra L in the middle seven lines of output. – Steven Rumbalski – 2013-03-28T14:56:17.607

You shouldn't...what version of Python are you using? – nneonneo – 2013-03-28T15:07:35.550

12

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

chyanog

Posted 2012-10-12T14:43:14.583

Reputation: 1 078

For the record: The is the Transpose operator (put it in Mathematica) – CalculatorFeline – 2016-02-28T04:57:20.970

1Very nice work. – DavidC – 2013-03-22T17:17:37.007

@DavidCarraher Thank you :D – chyanog – 2013-03-23T04:05:06.630

I echo David's remark. How did you come up with this? – Mr.Wizard – 2013-03-27T07:02:32.927

May I update your answer with the shorter modification I wrote? – Mr.Wizard – 2013-03-27T21:49:01.263

@Mr.Wizard Certainly. – chyanog – 2013-03-28T04:16:06.947

12

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}%

Howard

Posted 2012-10-12T14:43:14.583

Reputation: 23 109

1You 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 – 2013-03-28T16:21:13.890

10

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

tomsmeding

Posted 2012-10-12T14:43:14.583

Reputation: 2 034

damn it!! I missed the space and made half diamond. I must sleep now – Joomler – 2016-11-23T12:41:28.640

9

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

Gareth

Posted 2012-10-12T14:43:14.583

Reputation: 11 678

2nd one doesn't work. – Christian – 2013-03-22T04:30:05.983

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 – 2018-05-26T18:56:21.357

@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 – 2018-05-26T19:43:25.963

I meant, that I don't include <? in the bytecount. I've made some other improvements too. – RedClover – 2018-05-26T19:58:40.710

8

Charcoal (non-competing), 13 bytes

Not competing because the language is (much) newer than the question.

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 right one space before drawing the next one

DLosc

Posted 2012-10-12T14:43:14.583

Reputation: 21 213

4

This should be now competing as per new consensus in meta.

– officialaimm – 2017-09-13T08:16:55.710

7

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

copy

Posted 2012-10-12T14:43:14.583

Reputation: 6 466

7

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

Strigoides

Posted 2012-10-12T14:43:14.583

Reputation: 1 025

6

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

Iszi

Posted 2012-10-12T14:43:14.583

Reputation: 2 369

1You can save a byte by casting to a long instead of int64 – Veskah – 2018-07-26T20:50:19.117

Another way to save a byte 1..8+9..1|%{' '*(9-$_)+ +($x='1'*$_+'L')*$x} – mazzy – 2018-09-19T12:12:50.050

5

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

ngn

Posted 2012-10-12T14:43:14.583

Reputation: 11 449

5

Vim, 62 39 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

user41805

Posted 2012-10-12T14:43:14.583

Reputation: 16 320

You can delete the ma and change \ai<space>toI<space>`. – James – 2016-12-04T20:20:23.840

Also, you could probably delete stage 3 if you change stage 1 to pasting above and below. – James – 2016-12-04T20:21:46.653

@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 – 2016-12-05T08:37:36.377

4

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

Martin Ender

Posted 2012-10-12T14:43:14.583

Reputation: 184 808

4

k (64 50 chars)

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

Old method:

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

skeevey

Posted 2012-10-12T14:43:14.583

Reputation: 4 139

(1+!9)#'"1" is ,\9#"1" – ngn – 2016-12-05T22:42:35.403

4

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

Paolo

Posted 2012-10-12T14:43:14.583

Reputation: 696

+1 - can save a few with message(rep(" ",9-i),s[c(1:i,i:1-1)]) – flodel – 2015-04-11T17:14:50.760

@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 – 2017-12-14T17:10:40.277

64 bytes – Giuseppe – 2018-04-06T21:05:35.283

3

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

Leo

Posted 2012-10-12T14:43:14.583

Reputation: 8 482

3

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

Cr4xy

Posted 2012-10-12T14:43:14.583

Reputation: 31

Welcome to PPCG! – Евгений Новиков – 2017-07-04T10:53:19.440

3

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}%

Ilmari Karonen

Posted 2012-10-12T14:43:14.583

Reputation: 19 513

3

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

Mark Reed

Posted 2012-10-12T14:43:14.583

Reputation: 667

169 chars: f=->x{[*1..x]+[*1...x].reverse};puts f[9].map{|i|(f[i]*'').center 17} – Patrick Oscity – 2012-11-05T21:11:21.703

Great comment, I didn't know the '...' and didn't understand how this could work. – G B – 2016-11-25T07:10:36.880

60 chars: [*-8..8].map{|i|puts' '*i.abs+"#{eval [?1*(9-i.abs)]*2*?*}"} – G B – 2016-11-25T08:05:08.403

2

05AB1E, 17 15 10 bytes

9LJ.pû€û.c

Try it online!

Oliver Ni

Posted 2012-10-12T14:43:14.583

Reputation: 9 650

1

Based on Adnan's answer to a similar challenge, you can palindromize each substring and use the centering built-in: 9LJ.pû€û.c

– Osable – 2016-11-23T08:30:23.067

2

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.

Peter Taylor

Posted 2012-10-12T14:43:14.583

Reputation: 41 901

2

Matlab 227 223 221 209 208 bytes

z=@cellfun;
C=z(@(a,b,c)[a b c fliplr([a b])],[mat2cell(repelem(' ',36),1,8:-1:1),{''}],[{''},mat2cell(nonzeros(tril(repmat(49:56,8,1))')',1,1:8)],num2cell(49:57),'un',0)';
z(@(c)disp(c),[C;flipud(C(1:end-1))])

EBH

Posted 2012-10-12T14:43:14.583

Reputation: 221

2

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,'']

flawr

Posted 2012-10-12T14:43:14.583

Reputation: 40 560

2

PHP, 99 91 81 byte

for($y=17;$y--;print"
")for($x=17;$x--;)echo($d=9-abs($x-8)-abs($y-8))>0?$d:" ";

run in command line

php -r "CODE_ABOVE"

18 bytes saved by Jörg Hülsermann

Евгений Новиков

Posted 2012-10-12T14:43:14.583

Reputation: 987

you must not use open tags if you run PHP from the commndline with the -r option , replacing while with for loops and removing unnessaary spaces ends in Try it online!

– Jörg Hülsermann – 2017-07-04T11:07:00.413

@JörgHülsermann It works in ubuntu, but not in tio.run Do you know why? – Евгений Новиков – 2017-07-04T11:44:37.817

I understand not really the question cause I have linked a working tio.run example. tio.run is not the same as the command line so you need not to use options – Jörg Hülsermann – 2017-07-04T11:56:52.193

@JörgHülsermann first i seen about r option. Second about for, new line and other hacks. In fact in tio don't support two line arguments – Евгений Новиков – 2017-07-04T12:01:15.533

You need no arguments or input in this case and the bytecount is 80 – Jörg Hülsermann – 2017-07-04T12:04:24.973

@JörgHülsermann And how i can remove tags without commandline options? – Евгений Новиков – 2017-07-04T12:06:08.107

Let us continue this discussion in chat.

– Евгений Новиков – 2017-07-04T12:06:43.190

74-1 bytes: while($p++<263)echo$p%17?($d=0|9-abs($p%17-8)-abs($p/17-8))>0?$d:" ":"\n"; (-1 with a physical linebreak). Run with php -nr '<code>'.TiO

– Titus – 2018-12-21T13:17:52.793

@JörgHülsermann $argv and $argc are always set; at least if you run php from the command line. -r or -R are used to run snippets without tags. My guess is that tio.run and http://sandbox.onlinephpfunctions.com use exec php with a custom ini file (for timeout and forbidden functions).

– Titus – 2018-12-21T13:27:22.143

2

Gaia, 9 bytes

9┅…ṫ¦€|ṫṣ

Explanation

9┅         Push [1 2 3 4 5 6 7 8 9]
  …        Prefixes; push [[1] [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

Business Cat

Posted 2012-10-12T14:43:14.583

Reputation: 8 927

2

Jelly,  22 18 12  11 bytes (non-competing)

9ŒḄr1z⁶ṚŒḄY

Try it online!

Done alongside caird coinheringaahing in chat.

How it works

9ŒḄr1z⁶ṚŒḄY - Full program.

9ŒḄ         - The list [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1].
   r1       - Generate [N, N-1, ..., 1] for each N in ^.
     z⁶     - Zip; transpose ^ with filler spaces.
       Ṛ    - Reverse.
        ŒḄ  - Palindromize without vectorization.
          Y - Join by newlines.

Saved 6 bytes thanks to Leaky Nun!

Mr. Xcoder

Posted 2012-10-12T14:43:14.583

Reputation: 39 774

12 bytes – Leaky Nun – 2017-10-21T20:22:53.280

111 bytes – Leaky Nun – 2017-10-21T20:33:59.413

2

PowerShell, 49 48

1..9+8..1|%{"  "*(9-$_)+(1..$_+($_-1)..0|?{$_})}

Rynant

Posted 2012-10-12T14:43:14.583

Reputation: 2 353

Nice solution, though it has a lot of spacing not called for in the challenge. Helped me trim mine down to half its original size. – Iszi – 2013-11-24T02:24:47.703

2

Canvas, 7 bytes

9{R⇵]↶┼

Try it here!

Explanation:

9{R⇵]↶┼  
9{  ]    map over i = 1..9
  R        push a range 1..i
   ⇵       and reverse that array
         in Canvas, an array of arrays is a list of lines,
          and the inner arrays are joined together
     ↶   rotate anti-clockwise
      ┼  and quad-palindromize with 1 overlap

I've just fixed a couple built-ins to make a 6 byte version possible:

9{R]/┼

Try it here!

9{R]/┼
9{ ]    map over 1..9
  R       create a range 1..i
    /   pad with a diagonal of spaces
     ┼  and quad-palindromize

dzaima

Posted 2012-10-12T14:43:14.583

Reputation: 19 048

2

APL, 24 chars

⍉⊃{⍕⍵↑⍨⍵>0}¨9-∘.+⍨|9-⍳17

Tested in Nars2000 and Dyalog (requires ⎕ML←3 in the latter.)

Explanation

                     ⍳17    starting with the naturals up to 17
                  |9-       generate the numbers from 8 to 0 and back to 8
              ∘.+⍨          make a table of their sum (with 0 in the middle)
            9-              turn it into a diamond with 9 in the middle
  {       }¨                for each number
    ⍵↑⍨⍵>0                  keep it only if it's positive
   ⍕                        then convert the result, if any, to a string
⍉⊃                          disclose the nested array and adjust the dimensions

The last step transposes the result, whose shape is 17 17 1 (because of the disclose of nested strings) into 1 17 17, which gets printed like a plain 17 17.

Output

⍉⊃{⍕⍵↑⍨⍵>0}¨9-∘.+⍨|9-⍳17
        1        
       121       
      12321      
     1234321     
    123454321    
   12345654321   
  1234567654321  
 123456787654321 
12345678987654321
 123456787654321 
  1234567654321  
   12345654321   
    123454321    
     1234321     
      12321      
       121       
        1        

Tobia

Posted 2012-10-12T14:43:14.583

Reputation: 5 455

1Take the train to save a byte: (⍕>∘0↑⊢) – Adám – 2016-07-11T06:03:05.843

2

Bash, 126 109 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 :).

pawel.boczarski

Posted 2012-10-12T14:43:14.583

Reputation: 1 243

2

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

ardnew

Posted 2012-10-12T14:43:14.583

Reputation: 2 177

2

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

chinese perl goth

Posted 2012-10-12T14:43:14.583

Reputation: 1 089

2

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""}

Marco Martinelli

Posted 2012-10-12T14:43:14.583

Reputation: 293

added a 57 char groovy solution. You can replace both each with any to save two chars. – Matias Bjarland – 2017-02-12T10:52:37.347

2

Python, 65

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

cardboard_box

Posted 2012-10-12T14:43:14.583

Reputation: 5 150

Try prepending I=int; to your code and replacing all subsequent instances of int with I – Cyoce – 2016-11-27T02:51:38.960

@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 – 2016-11-27T04:05:10.620

2

Perl 6, 42 41 38 35 chars

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

Try it online!

Konrad Borowski

Posted 2012-10-12T14:43:14.583

Reputation: 11 185

@FrownyFrog Something did change in Perl 6 since this was written (this is a very old answer), fixed. – Konrad Borowski – 2018-07-27T12:42:38.857

2

Scala - 86 characters

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

Rex Kerr

Posted 2012-10-12T14:43:14.583

Reputation: 903

2

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)

Nippey

Posted 2012-10-12T14:43:14.583

Reputation: 121

1

Ruby 59

(-8..8).map{|i|puts' '*i.abs+"#{eval [?1*(9-i.abs)]*2*?*}"}

G B

Posted 2012-10-12T14:43:14.583

Reputation: 11 099

1

Ruby, 55

puts (-8..8).map{|i|[?\s*a=i.abs,(?1*(9-a)).to_i**2]*''}

Output:

irb(main):342:0> puts (-8..8).map{|i|[?\s*a=i.abs,(?1*(9-a)).to_i**2]*''}
        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1

Vasu Adari

Posted 2012-10-12T14:43:14.583

Reputation: 941

1

Groovy, 62, 57 chars

((1..9)+(8..1)).any{println' '*(9-it)+('1'*it as int)**2}

old version:

((1..9)+(8..1)).any{println"${('1'*it as int)**2}".center(17)}

explanation: we create a list [1,2,...,9,8,7,..,1]. Within the closure we create strings '1', '11', '111,..., convert them to numbers, run power of two and center.

Matias Bjarland

Posted 2012-10-12T14:43:14.583

Reputation: 420

1

Deadfish, 1446 bytes

iisiisddddooooooooiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddoddddsddddoooooooiiiiiiiiiiiiiiiiioiododddddddddddddddddddddddddddddddddddddddoddddsddddooooooiiiiiiiiiiiiiiiiioioiodododddddddddddddddddddddddddddddddddddddddoddddsddddoooooiiiiiiiiiiiiiiiiioioioiododododddddddddddddddddddddddddddddddddddddddoddddsddddooooiiiiiiiiiiiiiiiiioioioioiodododododddddddddddddddddddddddddddddddddddddddoddddsddddoooiiiiiiiiiiiiiiiiioioioioioiododododododddddddddddddddddddddddddddddddddddddddoddddsddddooiiiiiiiiiiiiiiiiioioioioioioiodododododododddddddddddddddddddddddddddddddddddddddoddddsddddoiiiiiiiiiiiiiiiiioioioioioioioiododododododododddddddddddddddddddddddddddddddddddddddodddsoioioioioioioioiodododododododododddddddddddddddddddddddddddddddddddddddoddddsddddoiiiiiiiiiiiiiiiiioioioioioioioiododododododododddddddddddddddddddddddddddddddddddddddoddddsddddooiiiiiiiiiiiiiiiiioioioioioioiodododododododddddddddddddddddddddddddddddddddddddddoddddsddddoooiiiiiiiiiiiiiiiiioioioioioiododododododddddddddddddddddddddddddddddddddddddddoddddsddddooooiiiiiiiiiiiiiiiiioioioioiodododododddddddddddddddddddddddddddddddddddddddoddddsddddoooooiiiiiiiiiiiiiiiiioioioiododododddddddddddddddddddddddddddddddddddddddoddddsddddooooooiiiiiiiiiiiiiiiiioioiodododddddddddddddddddddddddddddddddddddddddoddddsddddoooooooiiiiiiiiiiiiiiiiioiododddddddddddddddddddddddddddddddddddddddoddddsddddooooooooiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddo

A more human friendly spaced version:

iisiisdddd oooooooo iiiiiiiiiiiiiiiii o dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooooooo iiiiiiiiiiiiiiiii oiodo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooooo iiiiiiiiiiiiiiiii oioiododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooooo iiiiiiiiiiiiiiiii oioioiodododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooo iiiiiiiiiiiiiiiii oioioioiododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooo iiiiiiiiiiiiiiiii oioioioioiodododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oo iiiiiiiiiiiiiiiii oioioioioioiododododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd o iiiiiiiiiiiiiiiii oioioioioioioiodododododododo dddddddddddddddddddddddddddddddddddddddo
ddds oioioioioioioioiododododododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd o iiiiiiiiiiiiiiiii oioioioioioioiodododododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oo iiiiiiiiiiiiiiiii oioioioioioiododododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooo iiiiiiiiiiiiiiiii oioioioioiodododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooo iiiiiiiiiiiiiiiii oioioioiododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooooo iiiiiiiiiiiiiiiii oioioiodododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooooo iiiiiiiiiiiiiiiii oioiododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooooooo iiiiiiiiiiiiiiiii oiodo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooooooo iiiiiiiiiiiiiiiii o dddddddddddddddddddddddddddddddddddddddo

Uriel

Posted 2012-10-12T14:43:14.583

Reputation: 11 708

Any way to run this myself? – Metoniem – 2017-02-13T12:26:18.430

https://esolangs.org/wiki/Deadfish has implementation for most of the common programming languages – Uriel – 2017-04-03T21:51:11.957

Deadfish~ version. – None – 2019-10-13T14:14:07.423

1

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

Shmiddty

Posted 2012-10-12T14:43:14.583

Reputation: 1 209

1

///, 233 bytes

        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1

Try it online!

Yay.

Comrade SparklePony

Posted 2012-10-12T14:43:14.583

Reputation: 5 784

This is a polyglot. It should work in PHP, and some others also. – NoOneIsHere – 2017-02-24T23:13:42.140

@NoOneIsHere Yay. – Comrade SparklePony – 2017-02-24T23:38:38.370

1

k, 37 bytes

r:{x,1_|x};`0:`c$r@r'|8{32,-1_x}\49+!9

Try it online.

zgrep

Posted 2012-10-12T14:43:14.583

Reputation: 1 291

1

Japt -R, 19 18 17 16 11 bytes

9õõ ®¬êÃê û

Test it

Shaggy

Posted 2012-10-12T14:43:14.583

Reputation: 24 623

1

Recursiva, 31 22 bytes

{pB9'P+*" "- 9}J""WpB}

Try it online!

Explanation:

{pB9'P+*" "- 9}J""WpB}
{                       - For each
 p                      - palindromize [1,2,..9,..1]
  B9                    - range [1,2...9] 
    '                   - Iteration command begin
     P                  - Print
      +                 - concatenate
       *" "- 9 }        - appropriate number of spaces
                J""WpB} - obtain number string
                J""     - Join with nothing '123454321'
                   W    - map each element as string ['1','2'..'5','2','1']
                    p   - palindromize [1,2,..5,..2,1]
                     B} - range [1,2,3,4,5] 

officialaimm

Posted 2012-10-12T14:43:14.583

Reputation: 2 739

1

APL (Dyalog Classic), 21 bytes

{⊃⍵/⍕⍵}¨9-+/↑|8-⍳2⍴17

Try it online!

ngn

Posted 2012-10-12T14:43:14.583

Reputation: 11 449

1

APL (40)

r←{⍵,1↓⌽⍵}
{⎕←⍵,⍨' '⍴⍨(2×10-⌈/⍵)}¨r¨r⍳¨⍳9

I guess I'm not beating marinus. :p

protist

Posted 2012-10-12T14:43:14.583

Reputation: 570

1

T-SQL, 116 115 bytes

DECLARE @ INT=8,@d INT=-1a:PRINT SPACE(@)+STUFF('12345678987654321',9-@,2*@,'')IF @=0SET @d=1SET @+=@d If @<9GOTO a

Pure procedural counter and loop, not very "SQL"-like, but the best I could come up with using what SQL offers. Formatted:

DECLARE @ INT=8, @d INT=-1
a:
    PRINT SPACE(@)+STUFF('12345678987654321',9-@,2*@,'')
    IF @=0 SET @d=1
    SET @+=@d
If @<9 GOTO a

Cuts a length out of a hard-coded string using STUFF. Would work just as easily with any other set of characters.

BradC

Posted 2012-10-12T14:43:14.583

Reputation: 6 099

You can replace 10 with 9 and we get the same result (but saving 1 byte). – Razvan Socol – 2018-04-06T19:58:12.207

1

Python 2, 72 bytes

z="123456789"
for i in range(9)+range(8)[::-1]:print"% 8s"%z[:i]+z[i::-1]

Try it online!

ShadowCat

Posted 2012-10-12T14:43:14.583

Reputation: 11

Welcome to the site! I've edited in a link to an interpreter, so that others can test your solution – caird coinheringaahing – 2018-04-05T16:41:50.377

1

Stax, 10 bytes

▌┼î▲░ò╝╪.¢

Run and debug it

recursive

Posted 2012-10-12T14:43:14.583

Reputation: 8 616

1

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
]

Dorian

Posted 2012-10-12T14:43:14.583

Reputation: 1 521

1

MATL, 18 bytes

9Zv-9Zvq!-t0>48*+c

Try it on MATL Online

9Zv - symmetric range from [1:9 8:-1:1]

-9Zv - reverse symmteric range, [9:-1:1 2:9]

q! - decrement that to [8:-1:0 1:8] and transpose to vertical

- - broadcast subtract - matrix of each value in the second range subtracted from each value in the first range

t0> - duplicate that and get a logical matrix of 1s where it's > 0, 0s elsewhere

48* - multiply by 48 to change 1s to 48s (ASCII '0')

+ - add that to the original matrix

c - convert to char and implicitly display

sundar - Reinstate Monica

Posted 2012-10-12T14:43:14.583

Reputation: 5 296

1

R, 62 bytes

for(i in c(1:9,8:1))cat(rep(" ",9-i),1:i,(i:1)[-1],"
",sep="")

Try it online!

Giuseppe

Posted 2012-10-12T14:43:14.583

Reputation: 21 077

1

C++ 223 Byte

#include <iostream>
using std::cout;using std::size_t;int main(){for(int a=0;a<2;++a)for(size_t b=1+a*7;b<10-a;((a!=1)?++b:--b)){size_t c=9-b;for(;c-->0;)cout<<" ";for(c=1;c<b;)cout<<c++;for(c=b;0<c;)cout<<c--;cout<<'\n';}}

Ungolfed:

#include <iostream>
using std::cout; //for not having to type std::cout over and over again
using std::size_t; //for not having to type std::size_t over and over again

int main()
{
    for(int a = 0; a < 2; ++a)
        for(size_t b=1+a*7; b<10-a; ((a!=1)?++b:--b))
        {     //either count up to nine or down from nine
            size_t c = 9-b; //space count we need
            for(; c-- > 0;)
                cout << " ";
            for(c = 1; c < b;) //set c to the counter that will be print
                cout << c++; //post-crement :)
            for(c = b; 0 < c;) //count backwards
                cout << c--; //post-decrement :)
            cout << '\n'; //line is done
        }
}

NaCl

Posted 2012-10-12T14:43:14.583

Reputation: 528

Explanation please? – Lucas Henrique – 2015-04-12T16:38:23.793

@LucasHenrique updated – NaCl – 2015-04-12T17:20:18.250

1

K, 59

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

tmartin

Posted 2012-10-12T14:43:14.583

Reputation: 3 917

1

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

joequincy

Posted 2012-10-12T14:43:14.583

Reputation: 111

This gets the JS nod. It multiplies correctly. – Christian – 2013-03-22T04:37:30.523

1Instead of wrapping your for loops in brackets, use a semicolon. eg: for(j=0;j<a;j++)s+=" ";for(k... – Shmiddty – 2013-03-22T18:59:12.413

Thank you for pointing that out, @Shmiddty. I've adjusted the snippet. – joequincy – 2013-03-22T21:56:22.963

1

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

codeporn

Posted 2012-10-12T14:43:14.583

Reputation: 261

There is a bug: The rightmost digit in the center line is 0 in your output. – Thomas W. – 2012-11-19T13:40:52.270

I know, that is the mentioned precision problem also appearing in Nippeys second solution - do you know a fix for this? – codeporn – 2012-11-19T13:53:06.817

Oh, sorry, I see. No idea how to fix it--at least nothing that wouldn't make the code significantly larger. – Thomas W. – 2012-11-19T14:44:08.507

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. – codeporn – 2012-11-19T14:57:43.197

See joequncy answer below; http://codegolf.stackexchange.com/a/8742/7594

– Christian – 2013-03-22T04:38:00.023

0

Haskell, 77 bytes

r=[-8..8]
f n|n<1=" "|1>0=show n
mapM putStrLn[[9-abs x-abs y|x<-r]>>=f|y<-r]

Angs

Posted 2012-10-12T14:43:14.583

Reputation: 4 825

0

Excel VBA, 81 76 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the VBE Immediate Window

For i=-8To 8:j=Abs(i):r=Mid(987654321,j+1):?Spc(j)StrReverse(r)Mid(r,2):Next

Old Version, 81 Bytes

For i=-9To 8:For j=-8To 9:k=Abs(i)+Abs(j):l=l &IIf(k>8," ",9-k):Next:?l:l="":Next

Taylor Scott

Posted 2012-10-12T14:43:14.583

Reputation: 6 709

0

SmileBASIC, 65 bytes

FOR I=-8TO 8A=ABS(I)Q=VAL("1"*(9-A))?" "*A;Q*Q
NEXT
LOCATE 16,8?1

I used the fact that 11*11=121, 111*111=12321, etc. Unfortunately, 12345678987654321 can't be stored as a 64 bit float, so I had to add the last 1 separately, adding 14 bytes.

12Me21

Posted 2012-10-12T14:43:14.583

Reputation: 6 110

0

tcl, 122 110

proc P i {puts [format %[expr 8+$i]s [expr [string repe 1 $i]**2]]}
time {P [incr i]} 9
time {P [incr i -1]} 8

demo

sergiol

Posted 2012-10-12T14:43:14.583

Reputation: 3 055

0

Common Lisp SBCL, 145 bytes

(do((b 1)(l'(1 2 3 4 5 6 7 8 9))(i 1(+ i b)))((= i 0))(format t"~17:@<~v{~a~}~v{~a~}~>~%"i l i(reverse(subseq l 0(1- i))))(if(> i 8)(setf b -1)))

It is worse than the other Common Lisp solution, but it works and I think it is different enough to be posted.

Explanation

i is incremented up to 9 and then decremented to 0 (when i=9 sign of b is changed effectively changing addition to subtraction - this avoids second loop.

In each line I print numbers: `123...i(i-1)...1 using loops of format function (for first loop I use list '(1 2 3 4 5 6 7 8 9) and for decrementing loop I use reversed subsequence of this list. Text is then centered.

I didn't notice that numbers are squares of 11..11. As far as this solution is concerned the diamond could be made out of letters or (! @ # ...) (for that you would need to change ~a to ~c in format function.

user65167

Posted 2012-10-12T14:43:14.583

Reputation:

0

Python 2, 59 bytes

i=8;exec'print" "*abs(i)+`int("1"*(9-abs(i)))**2`;i-=1;'*17

Try it online!

Koishore Roy

Posted 2012-10-12T14:43:14.583

Reputation: 1 144

Alternate 59-byte solution: i=8;exec'print\int("1"(9-abs(i)))2`.center(18);i-=1;'17` – JosiahRyanW – 2018-09-20T18:10:12.457

Also, 58-bytes: i=8;exec'j=abs(i);print" "*j+\int("1"(9-j))2`;i-=1;'17` – JosiahRyanW – 2018-09-20T18:13:04.863

0

Yabasic, 89 bytes

Anonymous function that takes no input and outputs to STDOUT.

For i=-8To 8
For j=-8To 9
k=Abs(i)+Abs(j)
If k>8Then?" ";
Else?Chr$(57-k);
Fi
Next
?
Next

Try it online!

Taylor Scott

Posted 2012-10-12T14:43:14.583

Reputation: 6 709

0

///, 132 bytes

/T/123//F/T45//f/4321//S/  //s/S //N/
s//a/F678//b/765f//A/1Ns 121Ns/ssSAT21NSTfN FfNF65f
SF6b
 ab
a98b
 ab
SF6bNF65fN FfNSTfNsT2AS1

Try it online!

Erik the Outgolfer

Posted 2012-10-12T14:43:14.583

Reputation: 38 134

0

05AB1E, 9 bytes

žh¦η€ûû.c

Try it online!

Erik the Outgolfer

Posted 2012-10-12T14:43:14.583

Reputation: 38 134

0

Canvas, 14 bytes

9{:9∔ ×;R]∑9n┼

Try it here!

hakr14

Posted 2012-10-12T14:43:14.583

Reputation: 1 295

0

///, 124 bytes

/(/# '87#//'/"67//&/123//%/43!//$/  //#/654321
//"/&45//!/21
$ /$$$$1
$$$ 1!$ &!$&% "%"#$'('8987($'65%"65% "%$&%$ &!$$1!$$ 1

Try it online!

Shorter than this answer by 109 bytes! Just applies a bunch of substitutions with whitespace and common numbers.

Conor O'Brien

Posted 2012-10-12T14:43:14.583

Reputation: 36 228

0

Attache, 49 bytes

Print@Join=>Table[{If[_%9=_,9-_,sp]}@`+,Abs!-8:8]

Try it online!

Simply tables (that is, applies a function like a multiplication table) the function which adds two numbers (from [8, 7, 6, 5, ..., 5, 6, 7, 8]), checks if they are less than 9, then yields 9 - that number if so, otherwise a space. Then, prints each row accordingly.

Conor O'Brien

Posted 2012-10-12T14:43:14.583

Reputation: 36 228

0

Kotlin, 125 bytes

fun d(){for(i in 0..307){val v=Math.abs(i%18-9)+Math.abs(i/18-8)
print(if(i%18!=0)if(v>8)' '
else(57-v).toChar()
else '\n')}}

Try it online!

JohnWells

Posted 2012-10-12T14:43:14.583

Reputation: 611

0

Japt -R, 11 bytes

9õ_õ ¬êÃê û

Try it online!

Unpacked & How it works

9õZ{Zõ q ê} ê û

9õZ{  [1..9].map(Z=>...)
Zõ      [1..Z]
q       Join with nothing; ["1", "12", ..., "123...9"]
ê       Make palindrome;   ["1", "121", ..., "123...9...321"]
}
ê     Make palindrome on the array
û     Center-pad each element to the longest one
      `-R` joins with newline
      implicit output

I like the õ_õ emoji.

Bubbler

Posted 2012-10-12T14:43:14.583

Reputation: 16 616

0

C - 118 characters

x,c,i=1,j;main(){for(;i<20;){x=10;for(j=1;j<20;){j++<10?x--:x++;printf(x>c?" ":"%d",x);}i++<10?c++:c--;printf("\n");}}

My very first code golf! I still need to get into the golfing mindset, I know there is probably a lot I can do differently.

Edit: Try it online!

J.Barber

Posted 2012-10-12T14:43:14.583

Reputation: 31

Welcome to PPCG! – Luis felipe De jesus Munoz – 2018-07-26T20:50:34.857

1100 bytes – ceilingcat – 2018-12-23T07:25:38.637

0

Powershell, 45 bytes

1..9+8..1|%{' '*(9-$_)+-join(1..$_+$_..1|gu)}

2 solutions with 44 bytes were proposed in the comments to the Iszi's post

mazzy

Posted 2012-10-12T14:43:14.583

Reputation: 4 832

0

JavaScript, 84 bytes

Saved many bytes thanks to ETHProductions

[...s="12345678987654321"].map(x=>"".padEnd(9-x)+s.slice(0,x-1)+s.slice(-x)).join`
`

Try it online!

Oliver

Posted 2012-10-12T14:43:14.583

Reputation: 7 160

0

Tcl, 99 bytes

time {puts [string repe { } [expr abs([incr i]-9)]][expr [string repe 1 [expr 9-abs($i-9)]]**2]} 17

Try it online!

david

Posted 2012-10-12T14:43:14.583

Reputation: 479

0

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

for(int i=1,j=1;i>0;i+=j=i>8?-1:j)Write($"{"123456789".Substring(0,i),9}"+"87654321\n".Substring(9-i));

Try it online!

Definitely not the shortest answer, and this interpreter was published after the question was posted. But I did not see a C# answer. When using the regular C# compiler, the print statement is much longer: System.Console.Write. Also, string interpolation was not a thing when this question was posted.

dana

Posted 2012-10-12T14:43:14.583

Reputation: 2 541

0

Java, 155 chars

interface A{static void main(String[]a){var o=System.out;for(int i=-9,j,k;++i<9;o.println())for(j=-9;++j<9;)o.print((k=(i<0?-i:i)+(j<0?-j:j))>8?" ":9-k);}}

-7 chars thanks to a kind commenter.

Matthew Anderson

Posted 2012-10-12T14:43:14.583

Reputation: 131

0

Perl 5, 50 bytes

s/-//,$==8-$_,say$"x$_,map$=+1-abs,-$=..$=for-8..8

Try it online!

Denis Ibaev

Posted 2012-10-12T14:43:14.583

Reputation: 876

0

Excel, 24 chars (cheating?)

  1. In cell B2 put =MAX(A2,B1,B3,C2)-1 (19 chars)
  2. Fill down to B18 and right to R18.
  3. Select B2 through B18 and Format:Cells:Number:Custom: 0; (2 chars)
  4. Enter a 8.9 in J10 (3 char)
  5. Ignore all complaints about circular references throughout the process. Use Preferences:Calculation to allow iteration if it is not already allowed.
  6. Select columns B through R and resize their width to make square boxes.
  7. Profit?

Note: Some might call step 2 cheating as it creates 19 to 23 characters in every cell for a total of over 6000 chars. If you really want to count it that way, you would be better off not putting the formula into those squares that are to remain blank. In that case, you can use a 9 in J10 and you don't need the custom formatting. The total character count would then be just over 3000.

Wally

Posted 2012-10-12T14:43:14.583

Reputation: 483

0

C, 98 chars

l=9,n;p(i){for(i=18;i;putchar(i?n>l?48+n-l:32:10))n=9<--i?18-i:i;}
main(){p(l--);l&&p(main());l++;}

ugoren

Posted 2012-10-12T14:43:14.583

Reputation: 16 527

0

Java, 177 chars

public class A{public static void main(String[]v){
for(int a=-8,b,c;a<9;a++){
for(b=-8;b<9;){c=Math.abs(a)+Math.abs(b++);
System.out.print(c>8?" ":9-c);}System.out.println();}}}

correct formatting of this solution (352 chars):

public class A {
    public void main(String[] args) {
        for (int a = -8; a < 9; a++) {
            for (int b = -8; b < 9;) {
                int c = Math.abs(a) + Math.abs(b++);
                System.out.print(c > 8 ? " " : 9 - c);
            }
            System.out.println("");
        }
    }
}

Martin Thoma

Posted 2012-10-12T14:43:14.583

Reputation: 669

1You can trim off a few characters here and there. For example, String[] args can be String[]v, and System.out.println("") can be System.out.println(). Similarly, int b= -8; b < 9; can be int b=-8;b<9;. – arshajii – 2012-10-24T00:11:06.193

@A.R.S.: Thanks. Now it has 9 characters less (and is still by far the longest solution) – Martin Thoma – 2012-10-24T05:59:33.443

1You can spare 2 more characters by moving variable c's declaration into the for: for(int b=-8,c;b<9;){c=Math.…. – manatwork – 2012-10-24T06:41:00.223

1@manatwork: Thanks. I could remove 5 characters with this :-) And I've just seen that a VBA-solution is longer – Martin Thoma – 2012-10-24T07:34:32.200

Your class does not need the public modifier. – Poke – 2016-12-05T15:37:46.760

1You can remove all the newlines in your code – Poke – 2016-12-05T15:48:21.257

0

VBA, 197

for i=1 to 9:?string(27-i*3,32)l;:for j=1 to i:?j;:next:for j=i-1 to 1 step -1:?j;:next:?:next:for i=8 to 1 step -1:?string(27-i*3,32)l;:for j=1 to i:?j;:next:for j=i-1 to 1 step -1:?j;:next:?:next

if vba didn't automatically add a space for the + sign it doesn't print, perhaps I could avoid the 27-i*3 construct for making it look right

SeanC

Posted 2012-10-12T14:43:14.583

Reputation: 1 117