26
\$\begingroup\$

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!


Leaderboard

var QUESTION_ID=4114,OVERRIDE_USER=73772;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$

74 Answers 74

2
\$\begingroup\$

Java, 141

class t{public static void main(String a[]){char s[]=new char[21];s[9]='*';for(int i=0; i<10;System.out.println(s),s[9+i]=s[9-i]='0',i++);}}

Using a char array ..

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

Lua: 83, 89 or 97

A fixed-height 10-layer tree can be done in 83

a=string.rep
for i=0,9 do
print(i<1 and a(" ",8).."*" or a(" ",9-i)..a(0,i+i-1))end

Providing a height parameter takes it to 89

h=9
a=string.rep
for i=0,h do
print(i<1 and a(" ",h-1).."*" or a(" ",h-i)..a(0,i+i-1))end

Changing the first line to h=io.read() takes it up to 97, but allows the program to read the height from stdio.

Prints:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000

Note that the value of h is the size of the tree itself, excluding the star.

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

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

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

PHP, 136 Characters


        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000


;)

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

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.

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

Haskell, 73 characters

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

And the output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
\$\endgroup\$
1
\$\begingroup\$

Python, 64

Yet another python answer.

def f(i,c='0'):print' '*(9-i)+c*(i*2+1)
f(0,'*')
map(f,range(9))
\$\endgroup\$
1
\$\begingroup\$

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

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

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

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
\$\endgroup\$
  • \$\begingroup\$ The Main method does not need a string[] input parameter. It can be declared as: static void Main() \$\endgroup\$ – m0sa Mar 21 '12 at 19:15
  • \$\begingroup\$ @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. \$\endgroup\$ – ICR Mar 26 '12 at 14:41
  • \$\begingroup\$ Hmm, looks like my BF answer at least beats something... \$\endgroup\$ – Esolanging Fruit Dec 8 '16 at 6:38
1
\$\begingroup\$

V, 13 bytes (non-competing)

17é0òÄlxx>òr*

Try it online!

This is non-competing because V is newer than the challenge, but it's fun to beat the accepted answer by a huge margin. :D

Explanation:

17é0            " Insert 17 '0's
    ò     ò     " Recursively:
     Ä          "   Copy this line upwards
      l         "   Move one char to the right
       xx       "   Delete two characters
         >      "   Indent this line
           r*   " Replace the last character with an asterisk
\$\endgroup\$
1
\$\begingroup\$

Scala, 73 bytes

var(h,c)=(10,"*");0+:(0 to h-2)map{i=>println(" "*(h-i)+c*(i*2+1));c="0"}

Output

          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000
\$\endgroup\$
  • \$\begingroup\$ Welcome to Programming Puzzles and Code Golf. This is a very well golfed answer (+1), however it could benefit from a code breakdown and explanation. \$\endgroup\$ – wizzwizz4 Jan 10 '16 at 10:04
1
\$\begingroup\$

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

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

Ruby, 51 bytes

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

Output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
\$\endgroup\$
1
\$\begingroup\$

Whitespace, 2155 bytes

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

SSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSTSTSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSLLL

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.

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

F#, 167 bytes

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

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.

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

T-SQL, 151 bytes

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

Powershell, 38 bytes

' '*8+'*'
8..0|%{' '*$_+'0'*(17-2*$_)}

Output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000

Powershell with parameter, 49 bytes

param($h)' '*$h+'*'
$h..0|%{' '*$_+'0'*(17-2*$_)}
\$\endgroup\$
0
\$\begingroup\$

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

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.

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

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

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

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

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

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

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

Haskell

tree x=unlines $ (insert 1 '*'):[insert o '0'|o<-[1,3..r]]
    where insert n c=let sur = replicate ((r-n) `div` 2) ' ' in sur++(replicate n c)++sur
          r=2*x+1

Here is the output:

λ <*Main>: putStr $ tree 10
          *          
          0          
         000         
        00000        
       0000000       
      000000000      
     00000000000     
    0000000000000    
   000000000000000   
  00000000000000000  
 0000000000000000000 
000000000000000000000
\$\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.