90
\$\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

122 Answers 122

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 '13 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 '13 at 18:59
  • \$\begingroup\$ Thank you for pointing that out, @Shmiddty. I've adjusted the snippet. \$\endgroup\$
    – joequincy
    Mar 22 '13 at 21:56
1
\$\begingroup\$

APL (40)

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

I guess I'm not beating marinus. :p

\$\endgroup\$
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 '15 at 16:38
  • \$\begingroup\$ @LucasHenrique updated \$\endgroup\$
    – NaCl
    Apr 12 '15 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 '21 at 22:16
  • \$\begingroup\$ You can shorten this by 2 bytes; Try it online, 80 bytes \$\endgroup\$
    – Donat
    Mar 4 '21 at 16:38
1
\$\begingroup\$

k, 37 bytes

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

Try it online.

\$\endgroup\$
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\$

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

R, 62 bytes

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

Try it online!

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

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

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

Japt -R, 19 18 17 16 11 bytes

9õõ ®¬êÃê û

Test it

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

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.

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

Perl 5, 50 bytes

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

Try it online!

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

///, 139 bytes

/~/\/\///;/3&~|/*#~*/5432~&/2^~^/#!~%/$56~$/1234~#/1
~@/  ~!/@@/!!^@ 1&@12; $;$|@ %|@%76| %7876|%789876| %7876|@%76|@ %54;$54; $;@12;@ 1&!#

Try it online!

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

REXX, 86 chars

x='         12345678987654321 ' 
do n=1 to 17                    
m=9-abs(9-n)                    
say substr(x,m,10)right(x,m)    
end  

Complete program. No real tricks used except some smooshing and keeping to a single loop. I'm assuming EOL doesn't count.

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

Java, 156 chars

interface A{static void main(String[]v){for(int x,a=-9;++a<9;System.out.printf("%9s%s%n","123456789".substring(0,9-x),"87654321".substring(x)))x=a>0?a:-a;}}

Formatted version of this solution:

interface A {
  static void main(String[] v) {
    for (int x, a = -9; ++a < 9; System.out.printf("%9s%s%n", "123456789".substring(0, 9 - x), "87654321".substring(x)))
      x = a > 0 ? a : -a;
  }
}

Java code is generally longer. This is my shortest solution so far.

It does not produce additional whitespace in the right side as another solution does, but it is a little bit longer.

\$\endgroup\$
1
  • \$\begingroup\$ @ceilingcat: Nice, Thank you! \$\endgroup\$
    – Donat
    Jun 29 '20 at 7:40
1
\$\begingroup\$

T-SQL, 104 bytes

Inspired by @BradC's answer

DECLARE @ INT=8a:PRINT
space(abs(@))+stuff('12345678987654321',9-abs(@),abs(@)*2,'')SET
@-=1IF~@<8GOTO a

Try it online

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

Clojure, 115 bytes

(defn s[n](concat(range 1 n)(range n 0 -1)))(print(apply str(mapcat #(concat(repeat(- 9 %)" ")(s %)'("\n"))(s 9))))

Try it online!

Shortened from 127 to 121 to 115.

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

Java (JDK), 132 bytes

interface A{static void main(String[]v){for(long m=0,a=0;++a<18;System.out.printf("%"+(a>9?26-a:8+a)+"d%n",m*m))m=a>9?m/10:m*10+1;}}

Try it online!

This is a different way to do it than my first answer for Java. It is using integer arithmetics. It is even shorter, maybe the shortest possible.

Formatted version of this code:

interface A {
  static void main(String[] v) {
    for (long m = 0, a = 0; ++a < 18; System.out.printf("%" + (a > 9 ? 26 - a : 8 + a) + "d%n", m * m))
      m = a > 9 ? m / 10 : m * 10 + 1;
  }
}

Or more readable:

class A {
  public static void main(String[] v) {
    for (long m = 0, a = 0; ++a < 18; ) {
      long width = a > 9 ? 26 - a : 8 + a;
      m = a > 9 ? m / 10 : m * 10 + 1;
      System.out.printf("%" + width + "d%n", m * m);
    }
  }
}
\$\endgroup\$
1
\$\begingroup\$

Python 3, 123 bytes

k=[]
for t in range(10):
    l=str(111111111**2)[:t]
    k.append(l.rjust(9)+l[:-1][::-1])
print("\n".join(k+k[:-1][::-1]))

Try it online!

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

Java 10 IntStream, 230 chars

interface A{static void main(String[]a){f(i->{var o=System.out;f(j->o.print(i+j>8?" ":""+(9-i-j)));o.println();});}static void f(java.util.function.IntConsumer c){java.util.stream.IntStream.range(-8,9).map(Math::abs).forEach(c);}}

Try it online!

Readable:

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

    static void f(java.util.function.IntConsumer c) {
        java.util.stream.IntStream.range(-8, 9).map(Math::abs).forEach(c);
    }
}
\$\endgroup\$
1
\$\begingroup\$

MathGolf, 11 bytes

9╒ñmÆ╒ñyFΩn

Try it online.

Explanation:

9╒           # Push a list in the range [1,9]
  ñ          # Palindromize it: [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]
   m         # Map over each inner integer,
    Æ        # using the following five character as inner code-block:
     ╒       #  Convert the integer to a list in the range [1,n]
      ñ      #  Palindromize it similar as before
       y     #  Join the list together to a string
         Ω   #  Prepend/append potential leading/trailing spaces (centralize)
        F    #  to make the string length 17
          n  # After the map: join the strings in the list by newlines
             # (after which the entire stack is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

C (gcc), 171 163 147 142 bytes

-5 bytes thanks to @ceilingcat

#define f(x,y);for(j=0;j++<(i<9?x:y);)printf(
j;D(i){for(i=0;++i<19;puts("")){f(9-i,i-9)" ")f(i,18-i)"%d",j)f(i-1,17-i)"%d",i<9?i-j:18-i-j);}}

Try it online!

This code first prints a certain amount of spaces and then the numbers.

166 bytes

i,j;D(){for(;++i<19;){for(j=0;++j<19;i<10?(i+j>9&&j-i<9?printf("%d",j<9?i+j-9:9-j+i):printf(" ")):i-j<9&&i+j<27?printf("%d",j<9?j-i+9:27-i-j):printf(" "));puts("");}}

Try it online!

This code always chooses whether to print a space or a number, depending on the values of i and j.

\$\endgroup\$
1
  • \$\begingroup\$ @ceilingcat thank you. The semicolon at the start of the macro is a nice and original idea \$\endgroup\$ Jan 18 '21 at 15:30
1
\$\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\$
1
\$\begingroup\$

Lua, 80 bytes

for i=-8,8 do x=9-math.abs(i)n=math.ceil(10^x-1)//9print((" "):rep(9-x)..n*n)end

Try it online!

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

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.