Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

The Challenge

Print a nice Christmas tree with it's own star at the top using the shortest code possible. The tree star is an asterisk (*) and the tree body is made out of 0 The tree must be 10 rows high. Every row should be properly indented in the way that the previous row are centered over the next one. Any given row must have 2 more 0s than the previous, except for the first one that is the star and the second, which has only one 0. The result is something like this:

          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000

Tie break for resizable height trees without software changes (except changing height parameter)

Please, paste the resulting tree of your code too!

share|improve this question
3  
Not exactly a duplicate but there's this one on SO: Code Golf Christmas Edition: How to print out a Christmas tree of height N – Hasturkun Dec 5 '11 at 16:39

57 Answers

1 2

Java, 177 Chars

import java.util.Arrays;class C{public static void main(String[]a){
char[]r=new char[17];r[8]='*';int c=10;while(c-->0){if(c<9)Arrays.fill(r,c,17-c,'0');System.out.println(r);}}}

(Line break after main(...){ only for better readability.)

Uses API method Arrays.fill() to reduce number of while loops.

Prints this tree:

        *        
        0        
       000       
      00000      
     0000000     
    000000000    
   00000000000   
  0000000000000  
 000000000000000 
00000000000000000
share|improve this answer

Java, 230 characters

My own take.

class p{public static void main(String[]a){new p().m();}void m(){int h=0;x(20,1,"*");while(h<9)x(20-h,2*h+++1,"0");}void x(int s,int f,String c){for(;s>0;s--)d(" ");while(f-->0)d(c);d("\n");}void d(String s){System.out.print(s);}}

And the output:

                *
                0
               000
              00000
             0000000
            000000000
           00000000000
          0000000000000
         000000000000000
        00000000000000000

The code indented:

class p {
public static void main(String[] a) {
    new p().m();
}

void m() {
    int h = 0;
    x(20, 1, "*");
    while (h < 9)
        x(20 - h, 2 * h++ + 1, "0");
}

void x(int s, int f, String c) {
    for (; s > 0; s--)
        d(" ");
    while (f-- > 0)
        d(c);
    d("\n");
}

void d(String s) {
    System.out.print(s);
}
}

Adding parameters for height should take only a few more characters, but I am very far way of winning :P

share|improve this answer

Java, 147 chars (or 153)

class V{public static void main(String[]a){int c=10,i=-1,j;while(++i<c){for(j=0;++j<c+i;)System.out.print(j>c+i-2?i<1?"*\n":"\n":j<c-i?" ":"0");}}}

I based this on Daniel Schneller's solution, although I changed a lot. In line with Daniels solution, this one can be parameterized as well, where the number of command line parameters represents the height of the tree:

class V{public static void main(String[]a){int c=a.length,i=-1,j;while(++i<c){for(j=0;++j<c+i;)System.out.print(j>c+i-2?i<1?"*\n":"\n":j<c-i?" ":"0");}}}

Output (how surprising :):

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
share|improve this answer

PHP, 136 Characters


        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000


;)

share|improve this answer
1  
Now make the size adjustable. :) – Ilmari Karonen Dec 6 '11 at 21:45
Well, I can't make this size adjustable, but I could write meta-programs which can generate PHP programs like these of arbitrary size ;). – Weston C Dec 7 '11 at 0:55

Haskell, 83 chars

r=replicate
main=mapM_ putStrLn$(r 8' '++"*"):map(\x->r(9-x)' '++r(x*2-1)'0')[1..9]

...not as short as I thought it might be.

share|improve this answer

Haskell, 73 characters

main=mapM_ putStrLn$"        *":take 9(iterate((++"00").tail)"        0")

And the output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
share|improve this answer

Python, 64

Yet another python answer.

def f(i,c='0'):print' '*(9-i)+c*(i*2+1)
f(0,'*')
map(f,range(9))
share|improve this answer

F#, 167 Characters

let r n s=String.replicate n s
let rec x h i=
 let w=r i" "
 match h with|0->w+"*\n"|1->(x(h-1)i)+w+"0\n"|z->(x(h-1)(i+1))+w+(r(z+z-1)"0")+"\n"
printfn "%s"(x 8 0)
share|improve this answer

Ruby, 51

puts' '*8+'*';9.times{|a|puts' '*(8-a)+'0'*(a*2+1)}

Output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
share|improve this answer
Alas, there's already a shorter Ruby solution. – Ilmari Karonen Dec 10 '11 at 17:43

Java, 155 127

enum t{_;{for(char c=42,i=9,j;--i<0;c=48){j=i;String b="";while(--j>0)b+=" ";while(++j<(10-i)*2)b+=c;System.out.println(b);}}}

and a tree

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
share|improve this answer

with sed:

$ echo $'\n\n\n\n\n\n\n\n\n'|sed -e '1{ s/^/        */;h;}' -e '2,${x;/ 0/s//000/;/\*/s//0/;h;}'

Output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
share|improve this answer

PHP - 109 characters

for($i=10,$j=1,$k=0;$i;$i--,$j+=2,$k=2)echo str_pad(str_repeat($j<2?'*':0,$j-$k),$i+$j-(!$k?1:2),' ',0)."\n";

Not the shortest code possible, but easily resizable with changing only the value of $i.

share|improve this answer

VALA, 181

void main(string[] argv){int i,h=int.parse(argv[1]);stdout.printf(string.nfill(h-1,' ')+"*\n");for(i=0;i<h;i++)stdout.printf(string.nfill(h-i-1,' ')+string.nfill(2*i+1,'0')+"\n");}

The result :

[damien@caturday ~]$ ./christmas_tree 5
    *
    0
   000
  00000
 0000000
000000000
share|improve this answer

C#, 181 Characters

using System;
class T{static void Main(string[]a){
int h=int.Parse(a[0])-2,i=0;
Console.WriteLine("*".PadLeft(h+1));
while(i<=h)
Console.WriteLine(new string('O',i++*2+1).PadLeft(h+i));
}}

Output:

        *
        O
       OOO
      OOOOO
     OOOOOOO
    OOOOOOOOO
   OOOOOOOOOOO
  OOOOOOOOOOOOO
 OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOO
share|improve this answer
The Main method does not need a string[] input parameter. It can be declared as: static void Main() – m0sa Mar 21 '12 at 19:15
@m0sa It's used to pick up the height from the command line arguments. You can of course make it shorter by hardcoding the height. – ICR Mar 26 '12 at 14:41

Whitespace (2155 characters)

Program (replace S,T,L with Space,Tab,Linefeed characters respectively):

SSSTSSSSSLTLSSSSSTSSSSSL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TSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSLLL

or download the whitespace-only program text-file christmas_tree.ws.

Output:

          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000

This program simply outputs the 164 successive characters that make up the ten rows of the tree (averaging just over 13 program characters per output character). No doubt there's a much shorter Whitespace program that uses some logic to generate the blocks of repeated tree characters.

share|improve this answer

T-SQL 151

declare @h int
set @h=10;with t as(select'*'+space(@h-1)as z,1 as i
union all
select replicate('0',i*2-1)+space(@h-i),i+1 from t)
select top(@h)z from t

The height of the tree can be adjusted (just change the value of the @h variable)

The query uses a Recursive CTE.

Test link: http://sqlfiddle.com/#!3/d41d8/1695 (from the "Run SQL" dropdown button, select "Plaintext Output")

If run from the SQL Management Studio select "Results to Text" and use this query, as SSMS displays the data left aligned:

declare @h int
set @h=10;with t as(select space(@h-1)+'*'as z,1 as i
union all
select space(@h-i)+replicate('0',i*2-1),i+1 from t)
select top(@h)z from t

Sample SQL Server Management Studio output:

z
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
         *
         0
        000
       00000
      0000000
     000000000
    00000000000
   0000000000000
  000000000000000
 00000000000000000
share|improve this answer

CSV-133 Characters

Thought I would Cheat Just a little on this one for a few laughs :)

        0,
       000,
      00000,
     0000000,
    000000000,
   00000000000,
  0000000000000,
 000000000000000,
00000000000000000
share|improve this answer

LOLCODE

CAN HAS STDIO?
HAI 1.2
IM IN YR LOOP UPPIN YR VAR TIL BOTH SAEM VAR AN 8
    VISIBLE " "!
IM OUTTA YR LOOP
VISIBLE "*"
I HAS A SPACES
SPACES R 8
I HAS A ZEROS
ZEROS R 1
IM IN YR LOOP UPPIN YR VAR TIL BOTH SAEM VAR AN 9
    IM IN YR LOOP UPPIN YR VAR2 TIL BOTH SAEM VAR2 AN SPACES
        VISIBLE " "!
    IM OUTTA YR LOOP
    IM IN YR LOOP UPPIN YR VAR2 TIL BOTH SAEM VAR2 AN ZEROS 
        VISIBLE "0"!
    IM OUTTA YR LOOP
    VISIBLE ""
    SPACES R DIFF OF SPACES AN 1
    ZEROS R SUM OF ZEROS AN 2
IM OUTTA YR LOOP
KTHXBYE

Output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
share|improve this answer

C 145

Takes its heigh param from argc, so set the number of rows by setting the number of arguments:

#define x printf
int main(int c){int i=-1,j=0;while(j++<c)x(" ");x("*");while(++i<c){for(j=-2;++j<c-i;)x(" ");for(j=0;++j<2*i;)x("0");x("\n");}}

To generate the ten line spec output, you call:

christmastree 1 2 3 4 5 6 7 8 9

Or if you'd prefer to hardcode the height, change c in this version:

#define x printf
int main(){int i=-1,j=0,c=10;while(j++<c)x(" ");x("*");while(++i<c){for(j=-2;++j<c-i;)x(" ");for(j=0;++j<2*i;)x("0");x("\n");}}
share|improve this answer

R, 68 characters

s=sprintf;cat(s('%10s','*'),s('% *s%0*d',9:1,'',1:9*2-1,0),sep='\n')

And here's a parameterized version:

n=12 # Tree height (without star)
s=sprintf;cat(s('%*s',n+1,'*'),s('% *s%0*d',n:1,'',1:n*2-1,0),sep='\n')

Old version, 85 characters

cat('         *\n         0\n');cat(sprintf('% *d%0*d',9:2,0,seq(2,16,2),0),sep='\n')

I know, not the prettiest - R is not that great at formatting output using compact code.

share|improve this answer

Python, 79 chars

s,h=1,10;print " "*(h-s/2)+"*"
for x in range(h):print " "*(h-s/2)+"0"*s;s=s+2
          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000
 0000000000000000000
share|improve this answer

R, 89 chars

A fixed-height 10-layer tree can be done in 89 characters:

cat(rep("",9),"*\n");for(i in 1:10)cat(rep(" ",10-i),rep("0",seq(1,20,2)[i]),"\n",sep="")

Providing a height parameter takes it to 97:

h=10;cat(rep("",h-1),"*\n");for (i in 1:h)cat(rep(" ",h-i),rep("0",seq(1,2*h,2)[i]),"\n",sep="")

Output:

         *
         0
        000
       00000
      0000000
     000000000
    00000000000
   0000000000000
  000000000000000
 00000000000000000
0000000000000000000
share|improve this answer

PHP-275 Chars

Count is not including any whitespace, resizable by changing function parameter number:

function Tenenbaum($n)
{
$r="<br/>";
$x=2;
$v=" ";
$z="0";
$l=str_repeat($v,$n);
echo "$l*$r".$l."0$r";

for($i=1;$i<=$n;$i++)
{
$s=$n-3;
$p=str_repeat($v,$s);
$q=str_repeat($z,5);
echo str_repeat($v,$n-$i).str_repeat($z,$i+$x).$r;

if($i==$n)
{
echo "$p$q$r$p$q$r$p$q";
}
$x+=1;
}
}

Tenenbaum(20);

Output:

                    *
                    0
                   000
                  00000
                 0000000
                000000000
               00000000000
              0000000000000
             000000000000000
            00000000000000000
           0000000000000000000
          000000000000000000000
         00000000000000000000000
        0000000000000000000000000
       000000000000000000000000000
      00000000000000000000000000000
     0000000000000000000000000000000
    000000000000000000000000000000000
   00000000000000000000000000000000000
  0000000000000000000000000000000000000
 000000000000000000000000000000000000000
00000000000000000000000000000000000000000
                 00000
                 00000
                 00000
share|improve this answer

PHP - 75

<?=($p='          ').'*
';for($s=' 0';$p=substr($p,1);$s.='00')echo"$p$s
";

For variable heights of 12 or below, modify the hard-coded padding in the above. (Code gets smaller the lower the height)

For variable heights of 13 or more use the following, height param is the second argument to str_pad. (Code starts at 77 bytes and doesn't grow as fast as the version with static padding)

<?=($p=str_pad('',13)).'*
';for($s=' 0';$p=substr($p,1);$s.='00')echo"$p$s
";

Output of php -d short_open_tag=1 tree.php

          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000
share|improve this answer

VimScript: 92 characters

I am working at learning Vim and it occurred to me that it could be a neat platform for code golfing. I don't know how to script in Vim that well yet, so any optimization suggestions are appreciated. Note: ^[ does not mean a literal caret next to a literal bracket, but is Vim's way of displaying a literal ESC character in the text.

norm8a ^[a*^[9o^[17a0^[ka ^[15a0^[k2a ^[13a0^[k3a ^[11a0^[k4a ^[9a0^[k5a ^[7a0^[k6a ^[5a0^[k7a ^[3a0^[k8a ^[a0

Here is the output. One of the unique things about this answer is that the output is created in a buffer in Vim (use a :new buffer). The brackets indicate the final cursor location, which ended up where it did for optimization reasons but I think that is cool:

        *
       [0]
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000

Updated: 71 characters

Using mapping to reduce number of characters:

map b a0^[k
map c a ^[
norm8ca*^[9o^[17bc15b2c13b3c11b4c9b5c7b6c5b7c3b8ca0

Updated: 69 characters

Use punctuation instead of letters for the mapped characters in order to save two space characters.

map- a0^[k
map. a ^[
norm8.a*^[9o^[17-.15-2.13-3.11-4.9-5.7-6.5-7.3-8.a0

Updated: 66 characters

Use nn ("normal, no remap") for map to save 2 letters. Also swap final a0 for -. Note that this results in the cursor resting on the star in the final output rather than on the tip-top of the tree right below the star.

nn- a0^[k
nn. a ^[
norm8.a*^[9o^[17-.15-2.13-3.11-4.9-5.7-6.5-7.3-8.-

Updated: 63 characters

Moving/substituting a few more things allows yet another reduction (ignore the , -> . change):

nn- a0^[O^[
nn, a ^[
norm17-,15-2,13-3,11-4,9-5,7-6,5-7,3-8,-8,a*
share|improve this answer

Common Lisp - 100 [nonblank] chars

No Common Lisp solutions? =) Here's mine:

(or 
   (format t "~17:@<*~>~%") 
   (format t "~{~17:@<~{0~*~}~>~%~}" 
      (loop for x upto 8 collect 
         (make-list (1+ (* 2 x))))))

result:

        *        
        0        
       000       
      00000      
     0000000     
    000000000    
   00000000000   
  0000000000000  
 000000000000000 
00000000000000000

for higher trees just replace "8" with (height - 2) and "17" with 1+2x(height-2). Here's a 14 rows tree:

CL-USER> (or 
          (format t "~25:@<*~>~%") 
          (format t "~{~25:@<~{0~*~}~>~%~}" 
                  (loop for x upto 12 collect 
                       (make-list (1+ (* 2 x))))))
            *            
            0            
           000           
          00000          
         0000000         
        000000000        
       00000000000       
      0000000000000      
     000000000000000     
    00000000000000000    
   0000000000000000000   
  000000000000000000000  
 00000000000000000000000 
0000000000000000000000000
share|improve this answer

Java

package com.aschroder.christmastree;

public class ChristmasTreeGenerator {

    public static void main(String[] args) {

        System.out.println(
                "        *\n" + 
                "        0\n" + 
                "       000\n" + 
                "      00000\n" + 
                "     0000000\n" + 
                "    000000000\n" + 
                "   00000000000\n" + 
                "  0000000000000\n" + 
                " 000000000000000\n" + 
                "00000000000000000");
    }

}

Output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
share|improve this answer
9  
The point of code golf is to write the shortest possible program, abusing syntax as much as the compiler will allow. You should be able to reduce this program by at least 50% in length. – Peter Taylor Dec 6 '11 at 8:48
1 2

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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