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

17
\$\begingroup\$

Golfscript, 27 characters

" "9*"*"9,{n\.4$>\.+)"0"*}%

The resulting tree looks like this:

         *
         0
        000
       00000
      0000000
     000000000
    00000000000
   0000000000000
  000000000000000
 00000000000000000

A version which uses the height parameter only once is one character longer:

9." "*"*"@,{n\.4$>\.+)"0"*}%

Reading the height from stdin (with input "10" to generate the example tree) takes the same amount of characters (28):

~,)" "*"*"@{n\.4$>\.+)"0"*}%
\$\endgroup\$
56
\$\begingroup\$

I know this doesn't comply with the spec, but I thought I'd try to add some diversity to the trees here by imitating this classic ASCII art Christmas scene by Joan G. Stark.

I didn't try to reproduce the whole picture — that would've been a bit too much — but just the tree, for which I present this 138-byte Perl program:

$_=join$/,qw'11| 8\2_2/ 9(\o/) 5---2/1\2--- 10>*<',map(11-$_.A.AA x$_,2..11),'9\|H|/';s/\d+/$"x$&/eg,s/A/substr">>>@*O<<<",rand 9,1/eg,say

And, of course, here's a sample of the output:

           |
        \  _  /
         (\o/)
     ---  / \  ---
          >*<
         >O><@
        <><<>><
       @><><>@<<
      @<O><*@*>>O
     OO@@*O<<<*<OO
    ><<>@><<>@<><><
   >><O<>>><@*>>><<O
  *<>*<><<>@><O*>><*<
 O><><<@<*>><O*@>O><>*
O<><<><@O>>*O*OO<><<>O>
         \|H|/

Try it online!

The code uses the Perl 5.10+ say feature, and so needs to be run with the -M5.010 (or -E) command line switch. (Actually, just replacing the say at the end with print would avoid that, at the cost of two more bytes and the loss of the newline after the last line of output.)

Note that the bulk of the tree is randomly generated, so the placement of the ornaments will vary between runs. The angel, the stand and the top row of the tree are fixed, though.


To keep this popular answer from being summarily deleted under a policy instituted after it was posted, here's a token spec-compliant solution as well (45 bytes, also Perl 5):

$_=$"x10 ."*";say,s/ 0/00/,s/\*?$/0/ while/ /

Try it online!

Like the program above, this one also needs to be run on Perl 5.10+ with the -M5.010 switch to enable the say feature. Obviously (this being a challenge) it produces the exact same boring output as all the other compliant entries, which I won't bother repeating here. (It's also trivially resizable by changing the number 10 to any other other value.)

\$\endgroup\$
  • 1
    \$\begingroup\$ Great! Not by the spec but I think the judges special award is for you! :) \$\endgroup\$ – Averroes Dec 5 '11 at 23:13
  • 6
    \$\begingroup\$ this kicks the specs' proverbial behind, +2 if I could. \$\endgroup\$ – Kris Dec 6 '11 at 6:49
  • 3
    \$\begingroup\$ Sorry, but per the rules, answers that don't meet the spec must be deleted. \$\endgroup\$ – mbomb007 Dec 7 '16 at 20:34
  • \$\begingroup\$ I'm deleting this post in compliance with our policy about answers not meeting the challenge specification. \$\endgroup\$ – Dennis Feb 27 at 12:30
  • 1
    \$\begingroup\$ Could you please move the valid answer to the top and add a header? \$\endgroup\$ – Dennis Feb 28 at 23:53
13
\$\begingroup\$

GolfScript (33 chars)

Fixed-height version:

;8:^' '*.'*'+\'0'+^{.(;'00'+}*]n*

Or for exactly the same length

;8:^' '*.'*'+n@'0'+^{.n\(;'00'+}*

The tree looks remarkably similar to everyone else's:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000

Version which takes height from stdin:

~((:^' '*.'*'+\'0'+^{.(;'00'+}*]n*

The start of the previous line is one of the better smilies I've made in a "useful" GolfScript program.

\$\endgroup\$
10
\$\begingroup\$

Shell script, 44 characters

printf %9c\\n \* 0|sed ':x
p;s/ 0/000/;tx
d'

Prints this tree:

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

Maple, 30 / 37 chars

Inspired by Mr.Wizard's Mathematica entry, I present this 30-char Maple 12 command:

<`*`,('cat(0$2*i+1)'$i=0..8)>;

Output:

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

I can also get rid of the brackets at the cost of seven more chars:

`*`;for i in$0..8 do;cat(0$2*i+1);od;

Output omitted — it looks just like above, only without the brackets. Unfortunately, I don't know any way to keep Maple from inserting blank lines between the output rows in text mode. It looks better in classic worksheet mode. I guess I could include a screenshot...

screenshot

(The screenshot shows an earlier 44-char version of the command, but I'm too lazy to retake it. The output is still the same.)

Oh, and yes, the size is fully adjustable: just replace the 8 with n-2 for an n-row tree. With the first solution, going above 25 rows (or 10 in the GUI) requires also setting interface(rtablesize = n), though.

(Ps. I thought I'd managed to beat GolfScript with the latest version, but alas...)

\$\endgroup\$
8
\$\begingroup\$

Perl, 42 chars

say$"x9,"*";say$"x(9-$_),"00"x$_,0for 0..8

Output:

         *
         0
        000
       00000
      0000000
     000000000
    00000000000
   0000000000000
  000000000000000
 00000000000000000

The height of the tree can be changed between 1 and 11 rows by replacing the 8 at the end with values from -1 to 9. Going above 11 rows requires also increasing the two 9s earlier in the code, which control how far from the left side of the screen the tree is indented.

\$\endgroup\$
  • \$\begingroup\$ This one have 11 rows :P Minor changes I guess \$\endgroup\$ – Averroes Dec 5 '11 at 15:22
  • \$\begingroup\$ @Averroes: Yeah, I first assumed it was supposed to be 10 rows plus the star, but then I actually counted the rows in the sample output and fixed it. \$\endgroup\$ – Ilmari Karonen Dec 5 '11 at 15:27
8
\$\begingroup\$

Groovy, 65

(p={c,r->println' '*(9-r)+(c*(r*2-1))})'*',1;(1..9).each{p'0',it}

Surprisingly, the tree looks like this:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
\$\endgroup\$
  • \$\begingroup\$ The 'post the tree output' part is for bringing some Christmas spirit to this site :P \$\endgroup\$ – Averroes Dec 5 '11 at 17:14
  • \$\begingroup\$ Also, yours have 11 rows too! \$\endgroup\$ – Averroes Dec 5 '11 at 17:14
  • \$\begingroup\$ I can fix that by adjusting the height parameter(s)! \$\endgroup\$ – Armand Dec 5 '11 at 17:21
8
\$\begingroup\$

Ruby, 46 characters

puts" "*8+?*;9.times{|i|puts"%8s0"%(v=?0*i)+v}

In order to change the height you would have to change both 8s and of course also the 9. The output of the program is as follows:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000

Edit: Inexcusably I omitted the output in the first submission.

\$\endgroup\$
  • 1
    \$\begingroup\$ You forgot to post the output. :) \$\endgroup\$ – Ilmari Karonen Dec 5 '11 at 20:28
7
\$\begingroup\$

PowerShell, 41

" "*8+"*";0..8|%{" "*(8-$_)+"0"+"0"*$_*2}

Unsurprisingly, outputs the same tree as everyone else's :-p

If you parametrize that 8, it will yield up to the size of your console, in, say, 48 characters:

" "*($w=8)+"*";0..$w|%{" "*($w-$_)+"0"+"0"*$_*2}

Or, as a full-blown script which takes an argument, 53 characters:

param($w)" "*$w+"*";0..$w|%{" "*($w-$_)+"0"+"0"*$_*2}

Called, it looks like:

PS>: Get-Tree.ps1 8
        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
\$\endgroup\$
7
\$\begingroup\$

Python 3: 62 characters

print(' '*9+'*',*('\n'+' '*(9-i)+'0'*(i*2+1)for i in range(9)))

Output:

        * 
        0 
       000 
      00000 
     0000000 
    000000000 
   00000000000 
  0000000000000 
 000000000000000
00000000000000000

Note that this essentially beats @Ante's answer by 11 characters, because that answer, when converted to Python 3, uses 73 characters.

Change each 9 to another value for a different height.

\$\endgroup\$
  • 3
    \$\begingroup\$ I think you can also lose the space before for. \$\endgroup\$ – badp Dec 6 '11 at 6:22
  • \$\begingroup\$ @badp Thanks—changed from 63 to 62! \$\endgroup\$ – Kazark Dec 6 '11 at 10:50
6
\$\begingroup\$

Python, 59

print' '*9+'*'
for i in range(9):print' '*(9-i)+'0'*(i*2+1)
\$\endgroup\$
  • \$\begingroup\$ Nice work—this demonstrates that though the answer by @Ante gets longer in Python 3, my Python 3 answer is shorter in Python 2 (print not a function). \$\endgroup\$ – Kazark Dec 6 '11 at 10:54
6
\$\begingroup\$

Prolog: 183 or 186

r(0,_,L,L).
r(N,C,L,[C|T]):-N>0,M is N-1,r(M,C,L,T).
y(S,T,C):-r(T,C,[10],X),r(S,32,X,Y),atom_codes(A,Y),write(A).
x(A,B):-A>0,y(A,B,48),C is A-1,D is B+2,x(C,D).
x(N):-y(N,1,42),x(N,1).

Prints:

         *
         0
        000
       00000
      0000000
     000000000
    00000000000
   0000000000000
  000000000000000
 00000000000000000
false.

Could be squeezed further for certain interpreters (e.g. using tab/1 on SWI)

Invoke with x(N). Where N is the number of rows in the actual tree (excluding star). Giving it a fixed height would bring it down to 183

\$\endgroup\$
6
\$\begingroup\$

C

This is Wade Tandy's C version but modified a little bit:

           ;
          int
         main(
        ){int i
       =-1,j=0,c
      =10;while(j
     ++<c){printf(
    " ");}{;printf(
   "*");}while(++i<c
  ){for(j=-2;++j<c-i;
 )printf(" ");for(j=0;
++j<2*i;){printf("0");}
          ;;;
        printf(
         "\n")
          ;}}
\$\endgroup\$
5
\$\begingroup\$

Mathematica, 50

MatrixForm@Prepend[Row/@Table[0,{n,9},{2n-1}],"*"]
\$\endgroup\$
5
\$\begingroup\$

Applesoft BASIC, 143 chars

Since this question reminds me of a homework assignment I had back in high school (when they were teaching on an Apple //e):

1INPUTH:X=(H*2)-2:C=(X/2):S$="*":O=0:GOSUB2:S$="0":FORO=0TOX-2STEP2:GOSUB2:NEXT:END
2FORS=0TOC-(O/2):?" ";:NEXT:FORI=0TOO:?S$;:NEXT:?"":RETURN

I used the JavaScript Applesoft BASIC found here: http://www.calormen.com/applesoft/

OUTPUT:

?10
          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000
\$\endgroup\$
5
\$\begingroup\$

Prolog: 127 characters

p:-write('        *'),h(1).
h(L):-(L<10,nl,w(L,-8),h(L+1));!.
w(L,N):-(N<9,N<L,(L>abs(N)->write('0');write(' ')),w(L,N+1));!.

Output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
true 

Used Prolog because I was not able to beat the Groovy record without looking at his code :(.

\$\endgroup\$
5
\$\begingroup\$

PostScript (with parameterised height), 114 characters

/h 9 def/b{{( )=print}repeat}def
h -1 0{dup h eq{dup b(*)=}if dup b h sub neg 2 mul 1 add{(0)=print}repeat()=}for

Output:

         *
         0
        000
       00000
      0000000
     000000000
    00000000000
   0000000000000
  000000000000000
 00000000000000000
0000000000000000000

What, you wanted it to print out?

\$\endgroup\$
4
\$\begingroup\$

JavaScript (Rhino: 108, Node: 114, Webkit Dev Console: 119, jQuery Plugin: 132)


Rhino is the shortest (at 108 characters) because (a) its print function has a short name and (b) it'll let you assign built-in functions into a shorter variable name. So:

h=10,p=print,m='0',a=Array(h-1),s=a.join(' ');p(s+'*\n'+s+m);while(h-->2){m+='00';a.pop();p(a.join(' ')+m);}


Node.js comes in a close second (at 114 chars) because its print function console.log has a longer name, but it'll let us assign that to a short variable as well:

h=10,p=console.log,m='0',a=Array(h-1),s=a.join(' ');p(s+'*\n'+s+m);while(h-->2){m+='00';a.pop();p(a.join(' ')+m);}


However, the Webkit Dev Console (and probably Firebug, too) thinks p=console.log is a bit too sneaky (when you try to call p(), it'll complain at you). So, we have to lengthen things out to 119 characters:

h=10,m='0',a=Array(h-1),s=a.join(' ');with(console){log(s+'*\n'+s+m);while(h-->2){m+='00';a.pop();log(a.join(' ')+m);}}

(Interestingly, with only saves us a character).


Finally... a jQuery plugin (still tweetable at 132 characters!):

$.fn.xms=function(h){var m='0',w=2,l=['*',m];while(w++<h)l.push(m+='00');$(this).css({textAlign:'center'}).html(l.join('\n<br/>'));}

And you can invoke it on the footer of this very page: $('#footer').xms(3)

Of course, it doesn't have to be a plugin... since we'd probably have to use a JavaScript console to add it to a page and invoke it, we could've just done a snippet of jQuery:

h=10,m='0',w=2,l=['*',m];while(w++<h)l.push(m+='00');$('#footer').css({textAlign:'center'}).html(l.join('\n<br/>'));

which weighs in at a more competitive 116 characters -- in fact, it beats out the other dev console implementation. But, then again, using jQuery and/or the browser's layout engine might be considered cheating. :)

\$\endgroup\$
4
\$\begingroup\$

C, 67

I know this is long over, but it's my first attempt at code golf, and I think I've got a pretty nice C solution.

Interestingly, I came up with this independently of @Patrick's very similar solution.

And yes, I won't win any ties with my hardcoded values ;) I'm quite pleased, anyway.

i;main(){for(;i<10;++i)printf("%*s%0*c\n",i?9-i:8,"",i*2,i?32:42);}
        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
Press any key to continue . . .
\$\endgroup\$
4
\$\begingroup\$

Oracle

select lpad('*', 11) from dual
union all
select rpad(' ', 10 - level) || rpad(' ', level * 2, '0') from dual
connect by level <= 9;


          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000

10 rows selected.
\$\endgroup\$
4
\$\begingroup\$

PHP, 106 characters

7 fewer than the previous:

<?php echo str_pad(' ',9)."*\n";for($i=0;$i<9;$i++){echo str_pad("",9-$i).str_pad("",($i*2)+1,"0")."\n";}
\$\endgroup\$
  • 2
    \$\begingroup\$ enable short tags and save yourself 3 chars, or use the <?= and save another 5 from the "echo ". \$\endgroup\$ – Brombomb Dec 6 '11 at 20:36
  • \$\begingroup\$ I know I'm 8 months late, but codegolf.stackexchange.com/a/6783/4967 :) \$\endgroup\$ – Leigh Jul 26 '12 at 22:38
4
\$\begingroup\$

LOLCODE, 527 bytes

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

Try it online!

Output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
\$\endgroup\$
  • 1
    \$\begingroup\$ This is code-golf, so please add the byte count of your submission to the header. \$\endgroup\$ – lirtosiast Sep 29 '15 at 19:25
4
\$\begingroup\$

Python, 70 characters

Not so short, but recursive solution :-)

def a(s):
 print s
 if s<"0":a(s[1:]+"00")
print" "*8+"*"
a(" "*8+"0")

Change 8's to set height.

\$\endgroup\$
4
\$\begingroup\$

Javascript, 119 characters

Outputs to firebug console

i=h=9;a=new Array(h);a[0]=a.join(' ');b=a.join('000');a[0]+='*';while(i)a[i--]=b.substr(i,h+i);console.log(a.join('\n'))


        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
\$\endgroup\$
  • 2
    \$\begingroup\$ This is 120 characters actually. \$\endgroup\$ – Rob Fox Dec 8 '11 at 13:05
3
\$\begingroup\$

PHP 113

Figured i'd chime in with a php version:

113 chars (adjust $h to change the height, the number of lines includes the star):

$h=10;for($n=0;$n<$h;$n++){$i=$n>0?$n:1;$c=$n<1?"*":"0";echo str_repeat(" ",$h-$i).str_repeat($c,($i*2)-1)."\n";}

I tried to make it short, not readable and we already knew php can't compete on conciseness so this isn't going to win anything, still a fun little puzzle tho.

output is as spec:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000
\$\endgroup\$
  • \$\begingroup\$ Hardcoding a litlle bit more, 103 chars, (you can't see the spaces in the first echo inside this comment) $n=0;echo" *\n";for($i=9;$i>0;$i--,print str_repeat(' ',$i).str_repeat('0',$n+9-$i)."\n",$n++); \$\endgroup\$ – Lucia Dec 6 '11 at 13:23
  • \$\begingroup\$ your hardcoded first line would go out of balance if you change the height of the tree tho :-( \$\endgroup\$ – Kris Dec 6 '11 at 13:50
3
\$\begingroup\$

C, 77

i;main(c){printf("%*c\n",c,42);while(i<c)printf("%*s%0*d\n",c-i,"",i++*2+1,0);}

Before reading the printf spec more carefully, I had this cute little number down to 138 chars:

#define x sprintf(b,
#define y printf(b,
i;main(c){char b[9]="%%%dc\n",*t="%%%ds%%0%dd\n";x b,c);y 42);while(i<c)x t,c-i,i++*2+1),y "",0);}
\$\endgroup\$
3
\$\begingroup\$

Java, 192 (198 with param)

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

Prints the requested tree:

        *           
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000

For variable height, slightly longer:

class W{public static void main(String[]a){int c=a.length,i=-1,j=0;String s="";while(j++<c)s+=" ";s+="*";while(++i<c){for(j=-2;++j<c-i;)s+=" ";for(j=0;++j<2*i;)s+="0";System.out.println(s);s="";}}}

Length of command line argument list determines height (e. g. java W a a a a a will give height 5).

(This is basically the Java version of Wade Tandy's C solution.)

\$\endgroup\$
  • \$\begingroup\$ I know this was posted a while ago :), but here are two things I see: 1. you can use an interface instead of a class in java 8 2. to save two characters, while (++i < c) { -> for (s += "*";++i < c;s = "") {, and remove the s += "*"; and the s = ""; \$\endgroup\$ – R.M Feb 2 '18 at 0:45
3
\$\begingroup\$

Vim, 18 bytes

17i0<esc>qqYPxr q8@qa*

Try it online in the backwards-compatible V interpreter!

Although this is a very similar approach as my V answer, this one is not non-competing since vim is crazy old. :)

Explanation:

17i0<esc>               " Insert 17 '0's
         qq     q       " Start recording into register 'q'
           YP           " Duplicate this line upwards
             x          " Delete one character
              r         " Replace this character with a space
                 8@q    " Playback macro 'q' 8 times
                    a*  " Append an asterisk
\$\endgroup\$
3
\$\begingroup\$

Scala, 74 bytes

val h=10;println(" "*h+"*");for(i<-0 to h-2)println(" "*(h-i)+"0"*(i*2+1))

h - height of the tree

Output

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

C, 80

i=9,k=10,j;main(F){while(i)putchar(++j<i?32:j<k?48-F*6:(i-=!F,k+=!F,F=j=0,10));}

Initialize k to the tree height, i to k-1. F is first line flag. Given no argument, then F should be 1 upon entry.

A slightly longer(81) version where f is non first line flag:

i=9,k=10,j,f;main(){while(i)putchar(++j<i?32:j<k?42+f*6:(i-=f,k+=f,f=1,j=0,10));}
\$\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.