100
\$\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
  • 5
    \$\begingroup\$ What is the winning criterion ? And is this a challenge or a golf ? \$\endgroup\$
    – Paul R
    Oct 12, 2012 at 15:33
  • 26
    \$\begingroup\$ I read "kolmogorov-complexity" as "code-golf". \$\endgroup\$
    – DavidC
    Oct 12, 2012 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, 2012 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, 2012 at 22:00
  • 3
    \$\begingroup\$ perlmonks.com/?node_id=891559 has perl solutions. \$\endgroup\$
    – b_jonas
    Oct 20, 2012 at 19:51

140 Answers 140

2
\$\begingroup\$

k, 37 bytes

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

Try it online.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
9
  • \$\begingroup\$ 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! \$\endgroup\$ Jul 4, 2017 at 11:07
  • \$\begingroup\$ @JörgHülsermann It works in ubuntu, but not in tio.run Do you know why? \$\endgroup\$ Jul 4, 2017 at 11:44
  • \$\begingroup\$ 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 \$\endgroup\$ Jul 4, 2017 at 11:56
  • \$\begingroup\$ @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 \$\endgroup\$ Jul 4, 2017 at 12:01
  • \$\begingroup\$ You need no arguments or input in this case and the bytecount is 80 \$\endgroup\$ Jul 4, 2017 at 12:04
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ You can replace 10 with 9 and we get the same result (but saving 1 byte). \$\endgroup\$ Apr 6, 2018 at 19:58
2
\$\begingroup\$

05AB1E, 17 15 10 bytes

9LJ.pû€û.c

Try it online!

\$\endgroup\$
1
2
\$\begingroup\$

Japt -R, 19 18 17 16 11 bytes

9õõ ®¬êÃê û

Test it

\$\endgroup\$
1
  • \$\begingroup\$ Nice, that’s what I had too \$\endgroup\$
    – noodle man
    Jan 31 at 18:43
2
\$\begingroup\$

Clojure, 160 bytes

(run! #(println(reduce str "" %))(map (fn[i](map #(let[x(- (if(> % 9)(- 9(- % 9))%)(- 9 i))](if(pos? x)x " "))(range 1 18)))(concat(range 1 10)(range 8 0 -1))))
\$\endgroup\$
2
  • \$\begingroup\$ Welcome to this platform. Nice solution! Better than the other solution for Clojure! I suggest, you link your code with TIO as most of the other contributors have done: <a href="tio.run/##RYxBCoMwFESvMo0I/…" title="Clojure – Try It Online">Try it online!</a> \$\endgroup\$
    – Donat
    Jul 12, 2020 at 20:06
  • \$\begingroup\$ Have also a look at my solution: Clojure, 127 \$\endgroup\$
    – Donat
    Jul 12, 2020 at 23:41
2
\$\begingroup\$

StupidStackLanguage, 468 bytes

avdqvdmffffffffqvvviifavvfblffffffflfifdflavvfbfffffflfififdfdflavvfbffffflfifififdfdfdflavvfbfffflfififififdfdfdfdflavvfbffflfifififififdfdfdfdfdflavvfbfflfififififififdfdfdfdfdfdflavvfbflfifififififififdfdfdfdfdfdfdfavvfbfififififififififdfdfdfdfdfdfdfdflavvfbflfifififififififdfdfdfdfdfdfdflavvfbfflfififififififdfdfdfdfdfdflavvfbffflfifififififdfdfdfdfdflavvfbfffflfififififdfdfdfdflavvfbffffflfifififdfdfdflavvfbfffffflfififdfdflavvfbffffffflfifdflavvfbfffffffflf

Try it online!

Explanation

Super simple, we just create a space and the number 1, then every line just increment and print then decrement and print

\$\endgroup\$
2
  • \$\begingroup\$ Wait, you're telling me this is a completely manual solution?! \$\endgroup\$
    – Razetime
    Oct 3, 2020 at 12:04
  • \$\begingroup\$ Yeah lol, not very efficient at all but I didn't have much time writing this answer, it can probably be compacted hugely. \$\endgroup\$
    – Lebster
    Oct 4, 2020 at 3:32
2
\$\begingroup\$

Zsh, 91 61 bytes

eval s+={1..9}';<<<${(l:8:)s%?}`rev<<<$s`;'>f;{<f;tac f}|uniq

Try it online!

eval s+={1..9}';<<<${(l:8:)s%?}`rev<<<$s`;'>f;{<f;tac f}|uniq

eval    {1..9}'                          ;'                    # evaluate this 9 times
     s+=       ;                                               #  append the number to s
                <<<                                            #  print
                   ${      s  }                                #   s
                            %?                                 #    with the last character removed
                     (l:8:)                                    #    padded to 8 spaces
                               `rev<<<$s`                      #   then s, reversed
                                          >f;                  # all output to the file f
                                              <f;              # print f
                                                 tac f         # print f in reverse
                                             {        }|uniq   # remove the duplicated line in the middle
```
\$\endgroup\$
2
\$\begingroup\$

JavaScript (V8), 75 bytes

for(a=9;b=--a>0?9-a:9+a;print(s))for(s='',c=9;--c+b;)s+=c<0?b+c:c<b?b-c:' '

Try it online!

\$\endgroup\$
2
\$\begingroup\$

JavaScript (V8), 75 bytes

for(b of x="12345678987654321")print(b-9?"".padEnd(9-b)+"1".repeat(b)**2:x)

Try it online!

Doing the calculations 1**2, 11**2, 111**2, ...

This solution fixes the precision problem. It correctly produces a 1 at the end of the longest line instead of 0. I think, this one is the clearest of the short solutions for JavaScript.

Instead of x="12345678987654321" you could also write x=111111111**2/10+"1" which is equally short.

\$\endgroup\$
2
\$\begingroup\$

JavaScript (Node.js), 73 bytes

for(z of(s=z=>"".padEnd(9-z)+(BigInt(10**z)/9n)**2n)(9))console.log(s(z))

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Templates Considered Harmful, 267 255 bytes

Ap<Fun<If<A<1>,Cat<Ap<Fun<Cat<Ap<Fun<If<A<1>,Cat<Ap<A<0>,Sub<A<1>,T>>,SP>,LF>>,Sub<I<9>,A<1>>>,Ap<Fun<If<lt<A<1>,A<2>>,Cat<Cat<A<1>,Ap<A<0>,Add<A<1>,T>,A<2>>>,A<1>>,A<1>>>,T,A<1>>>>,If<lt<A<1>,I<9>>,A<1>,Sub<I<18>,A<1>>>>,Ap<A<0>,Sub<A<1>,T>>>,LF>>,I<17>>

Try it online!

Has leading and trailing whitespace -- sorry! tch has no concept of "empty string" (at least not that I've found)

I doubt the ungolfed version would answer any questions (probably the opposite). I like to think of TCH as a lisp-like language with no functions, loops, or variables, so all the logic is done through recursive lambdas.

The basic structure:

lambda:  (run lower lambdas with int 1,2,3...,17,18, join output)
   lambda:  (convert input, run lower lambdas, join output)
     lambda:  (int -> string of spaces & newline)
     lambda:  (int -> string of numbers)
\$\endgroup\$
2
\$\begingroup\$

Vyxal, 14 bytes

9ɾ∞(9n-Inɾ∞Jṅ,

Try it Online!

Explanation

9ɾ∞(9n-Inɾ∞Jṅ,
9ɾ∞             Palindromise range from 1-9 incl.
   (            Start loop
    9n-I        Push n-9 spaces
        nɾ∞     Palindromise range from 1-n
           J    Join spaces with range
            ṅ,  Join everything by nothing and print it out
\$\endgroup\$
2
  • \$\begingroup\$ get outgolfed lol \$\endgroup\$
    – naffetS
    Jun 22, 2022 at 15:40
  • \$\begingroup\$ @Steffan what the heck \$\endgroup\$
    – math scat
    Jun 22, 2022 at 17:25
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

Go, 239 196 187 185 167 bytes

import(."fmt";."strings")
func g(i int){P:=Print
P(Repeat(" ",9-i))
j:=1
for;j<i;j++{P(j)}
for;j>0;j--{P(j)}
P(`
`)}
func f(){i:=1
for;i<9;i++{g(i)}
for;i>0;i--{g(i)}}

Attempt This Online!

My first attempt at golfing in Go.

-18 thanks to @c--

Commented (Old)

import (."fmt"; ."strings")        // Import modules for later
func g(i int) {                    // Helper function g taking an int i
P := Print                         //  Useful function for later
P(Repeat(" ", (9 - i)))            //  Repeat a space 9-i times and print
for j := 1; j <= i; j++ { P(j) }   //  Print each j for j in [1 .. i]
for k := i-1; k > 0; k-- { P(k) }  //  Print each k for k in [i .. 1]
P("\n") }                          //  Print a newline
func f(){                          // Function boilerplate
for i := 1; i < 10; i++ { g(i) }   //  Call g for each i in [1 .. 9]
for i := 8; i > 0; i-- { g(i) }}   //  Call g for each i in [8 .. 1]
\$\endgroup\$
0
2
\$\begingroup\$

owl lisp, 158 bytes

(map (λ (x) (map display (append (map (λ (_) " ") (iota 1 1 (- 10 x))) (iota 1 1 (+ 1 x)) (iota (- x 1) -1 0) `("\n")))) (append (iota 1 1 9) (iota 9 -1 0)))

un-golfed

(map (λ (x)
        (map display
             (append
               (map (λ (_) " ") (iota 1 1 (- 10 x)))
               (iota 1 1 (+ 1 x))
               (iota (- x 1) -1 0)
               `("\n"))))
     (append (iota 1 1 9)
             (iota 9 -1 0)))
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf, and nice first answer! \$\endgroup\$
    – The Thonnu
    Aug 26, 2023 at 7:35
2
\$\begingroup\$

Julia 1.0, 57 53 51 bytes

!i=[1:i;i-1:-1:1]
!9 .|>i->println(' '^(9-i),!i...)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

J, 20 bytes

(1{2{.":)@-9-+/~|i:8

Try it online! Exploits a few silly features of J, some of which are already present in other solutions.

(1{2{.":)@-9-+/~|i:8
                 i:8 NB. -8 -7 ... 7 8
                |    NB. abs
             +/~     NB. addition table: 16 in corner down to 0 in center
           9-        NB. subtract from 9: -7 in corner up to 9 in center
(       )@-          NB. for each number, negate and...
   2{.":             NB.  convert to string and right pad to width 2
 1{                  NB.  take second character

": prints negative signs so 2{.": gives a 2 character string which ends in a space for 0 through 9 and in a digit for -1 or less. Also of note is the symmetrical-integers-around-zero primitive i: which combines with absolute value | to give a terse palindrome of ints.

\$\endgroup\$
2
\$\begingroup\$

Swift, 132 131 130 bytes

let r={(1..<$0)+(1...$0).reversed()}
r(9).map{(0...9-$0).map{$0
print(terminator:" ")}
r($0).map{print($0,terminator:"")}
print()}
\$\endgroup\$
2
\$\begingroup\$

Jelly, 25 bytes

L_8Cx@32;
9RR€+48Ç€ŒBŒḄỌY

Definitely have some extra bytes because I get messed up on when and how things are converted to strings in jelly

L_8Cx@32;   # Replicate a space (ascii 32) 9-length amount of times
            # and prepend that to the original input

9RR€+48Ç€ŒBŒḄỌY
9R                 # [1..9]
  R€               # Each of those as a range
                   # [[1], [1,2], [1,2,3] ... ]
    +48            # Turn the number to ascii
       ǀ          # Call the space prepender (previous link) on each
         ŒB        # Mirror each element of the list
           ŒḄ      # Mirror the entire list (bottom half of diamond)
             ỌY    # Convert to characters and join with linefeeds
\$\endgroup\$
2
  • \$\begingroup\$ Welcome to code golf stack exchange, and nice submission! FYI, somebody already came up with a really cool 11-byte Jelly solution to this challenge: codegolf.stackexchange.com/a/145963/108687 You can search for submissions to a given challenge in a specific language by going to the search bar on that challenge’s page and typing inquestion:this jelly or whatever other language you’re looking for. \$\endgroup\$
    – noodle man
    Mar 21 at 1:13
  • \$\begingroup\$ oh, thank you @noodleman \$\endgroup\$
    – Aaron
    Mar 21 at 5:25
1
\$\begingroup\$

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:' '
\$\endgroup\$
1
\$\begingroup\$

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

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

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
        }
}
\$\endgroup\$
2
  • \$\begingroup\$ Explanation please? \$\endgroup\$ Apr 12, 2015 at 16:38
  • \$\begingroup\$ @LucasHenrique updated \$\endgroup\$
    – NaCl
    Apr 12, 2015 at 17:20
1
\$\begingroup\$

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]
\$\endgroup\$
2
  • \$\begingroup\$ This is not a complete runnable program. I think, you should add main= in the third line. Try it online. Would be 82 bytes then. \$\endgroup\$
    – Donat
    Mar 2, 2021 at 22:16
  • \$\begingroup\$ You can shorten this by 2 bytes; Try it online, 80 bytes \$\endgroup\$
    – Donat
    Mar 4, 2021 at 16:38
1
\$\begingroup\$

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] 
\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog Classic), 21 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ (assumes ⎕io←0) \$\endgroup\$
    – Mark Reed
    Mar 6 at 2:30
1
\$\begingroup\$

Python 2, 72 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to the site! I've edited in a link to an interpreter, so that others can test your solution \$\endgroup\$ Apr 5, 2018 at 16:41
1
\$\begingroup\$

///, 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.

\$\endgroup\$
1
\$\begingroup\$

Stax, 10 bytes

▌┼î▲░ò╝╪.¢

Run and debug it

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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