95
\$\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
  • 25
    \$\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

131 Answers 131

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\$
    – anotherOne
    Jan 18, 2021 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\$

Vyxal, C, 9 bytes

9ƛɾømĴ;ḆJ

Try it Online!

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

JavaScript (Node.js), 107 bytes

b=Math.abs,e="";for(i=0;i<17;i++){for(j=0;j<17;j++){z=9-(b(i-8)+b(j-8));e+=z>0?z:" "}e+="\n"}console.log(e)

Try it online!

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

C (gcc), 82 78 bytes

#define W printf("%*lld\n",i,1ll*j*j)
g(i,j){i<17&&g(W,j*10+1);W;}D(){g(9,1);}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ printf("%*ld\n",i,1l*j*j) \$\endgroup\$ Jul 22 at 23:13
1
\$\begingroup\$

Haskell, (complete program) 79 bytes

main=mapM putStrLn[(' '<$[n..8])++(s n>>=show)|n<-s 9]
s n=[1..n-1]++[n,n-1..1]

Try it online!

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

Excel, 80 bytes

=CONCAT(LET(x,ABS(9-ROW(1:17)),y,9-ABS(9-COLUMN(A:R)),IFS(y>x,y-x,y," ",1,"
")))

Link to Spreadsheet

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

Vyxal C, 17 bytes

»÷rṡF»S¦øṁ½ƛ÷⋎;øm

Explanation

»÷rṡF»S                - 123456789 as string
       ¦               - Take all the prefixes
        øṁ             - Vertical mirror
          ½ƛ÷⋎;        - Halve and split, then join while removing the duplicate ends.
               øm      - Horizontal palindromize.
<C flag>               - Center and join list by newlines
<implicit output>      - Print

Try it Online!

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

Perl 5, 33 bytes

say$"x abs.(1x(9-abs))**2for-8..8

Try it online!

Using 11 * 11 = 121, 111 * 111 = 12321, 1111 * 1111 = 1234321, ...

3 bytes saved thanks to naffetS.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 33: say$"x abs.(1x(9-abs))**2for-8..8 \$\endgroup\$
    – naffetS
    Mar 15 at 2:53
1
\$\begingroup\$

Java 8 (OpenJDK 8), 157 161 bytes

-4 bytes thanks to @ceilingcat

Tried to use only 1 for instead of 2 for two-dimensional printing, but couldn't beat the best Java answers.

interface M{static void main(String[]b){for(int r,s,a=0;a<289;System.out.print((r<1?s<1?" ":"":r)+(s>7?"\n":"")))r=9-Math.abs(s=a%17-8)-Math.abs(8-a++/17);}}

Try it online!

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

Swift, 132 bytes

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

JavaScript (V8), 77 78 bytes

-1 byte thanks to Donat!

Not the shortest JS solution, but not the longest either!

for(i=9;--i+9;)print(("".padEnd(a=i<0?-i:i)+"1".repeat(9-a)**2).replace(0,1))

Try it online!


i goes from 8 to -8.
We generate the correct number of spaces for each line by using the absolute value of i.

We take advantage of the fact that:

1 * 1 = 1
11 * 11 = 121
111 * 111 = 12321
1111 * 1111 = 1234321
(and so on)

So we generate the correct number of 1 by repeating it 9 minus the absolute value of i.

But unfortunately, JS can't handle properly the biggest calculation: 111111111 at power 2 gives 12345678987654320, so we also have to replace this single 0 with a 1, which costs 14 bytes :(

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You can substitute " ".repeat by "".padEnd and save one byte. \$\endgroup\$
    – Donat
    Jul 22 at 15:23
  • \$\begingroup\$ @Donat Thanks for your tip! I've updated my solution. \$\endgroup\$
    – Fhuvi
    Jul 24 at 7:59
0
\$\begingroup\$

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++;}
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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("");
        }
    }
}
\$\endgroup\$
8
  • 1
    \$\begingroup\$ You 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;. \$\endgroup\$
    – arshajii
    Oct 24, 2012 at 0:11
  • \$\begingroup\$ @A.R.S.: Thanks. Now it has 9 characters less (and is still by far the longest solution) \$\endgroup\$ Oct 24, 2012 at 5:59
  • 1
    \$\begingroup\$ You can spare 2 more characters by moving variable c's declaration into the for: for(int b=-8,c;b<9;){c=Math.…. \$\endgroup\$
    – manatwork
    Oct 24, 2012 at 6:41
  • 1
    \$\begingroup\$ @manatwork: Thanks. I could remove 5 characters with this :-) And I've just seen that a VBA-solution is longer \$\endgroup\$ Oct 24, 2012 at 7:34
  • 1
    \$\begingroup\$ You can remove all the newlines in your code \$\endgroup\$
    – Poke
    Dec 5, 2016 at 15:48
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

Python 2, 59 bytes

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

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Alternate 59-byte solution: i=8;exec'print`int("1"*(9-abs(i)))**2`.center(18);i-=1;'*17 \$\endgroup\$ Sep 20, 2018 at 18:10
  • \$\begingroup\$ Also, 58-bytes: i=8;exec'j=abs(i);print" "*j+`int("1"*(9-j))**2`;i-=1;'*17 \$\endgroup\$ Sep 20, 2018 at 18:13
0
\$\begingroup\$

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

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!

\$\endgroup\$

Your Answer

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

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