Print a Christmas Tree

26

13

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>

Averroes

Posted 2011-12-05T14:44:27.150

Reputation: 3 771

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 – 2011-12-05T16:39:56.653

Answers

17

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"*}%

Ventero

Posted 2011-12-05T14:44:27.150

Reputation: 9 842

56

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.)

Ilmari Karonen

Posted 2011-12-05T14:44:27.150

Reputation: 19 513

3Sorry, but per the rules, answers that don't meet the spec must be deleted. – mbomb007 – 2016-12-07T20:34:42.613

I'm deleting this post in compliance with our policy about answers not meeting the challenge specification.

– Dennis – 2019-02-27T12:30:36.233

1Could you please move the valid answer to the top and add a header? – Dennis – 2019-02-28T23:53:22.020

1Great! Not by the spec but I think the judges special award is for you! :) – Averroes – 2011-12-05T23:13:09.530

6this kicks the specs' proverbial behind, +2 if I could. – Kris – 2011-12-06T06:49:00.447

13

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.

Peter Taylor

Posted 2011-12-05T14:44:27.150

Reputation: 41 901

10

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

Evan Krall

Posted 2011-12-05T14:44:27.150

Reputation: 251

9

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...)

Ilmari Karonen

Posted 2011-12-05T14:44:27.150

Reputation: 19 513

8

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.

Ilmari Karonen

Posted 2011-12-05T14:44:27.150

Reputation: 19 513

This one have 11 rows :P Minor changes I guess – Averroes – 2011-12-05T15:22:30.973

@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. – Ilmari Karonen – 2011-12-05T15:27:28.433

8

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

Armand

Posted 2011-12-05T14:44:27.150

Reputation: 499

The 'post the tree output' part is for bringing some Christmas spirit to this site :P – Averroes – 2011-12-05T17:14:08.143

Also, yours have 11 rows too! – Averroes – 2011-12-05T17:14:36.457

I can fix that by adjusting the height parameter(s)! – Armand – 2011-12-05T17:21:06.583

8

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.

Howard

Posted 2011-12-05T14:44:27.150

Reputation: 23 109

1You forgot to post the output. :) – Ilmari Karonen – 2011-12-05T20:28:57.320

7

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.

Kazark

Posted 2011-12-05T14:44:27.150

Reputation: 289

3I think you can also lose the space before for. – badp – 2011-12-06T06:22:51.123

@badp Thanks—changed from 63 to 62! – Kazark – 2011-12-06T10:50:24.893

7

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

Jaykul

Posted 2011-12-05T14:44:27.150

Reputation: 223

6

Python, 59

print' '*9+'*'
for i in range(9):print' '*(9-i)+'0'*(i*2+1)

Patrick

Posted 2011-12-05T14:44:27.150

Reputation: 221

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). – Kazark – 2011-12-06T10:54:29.587

6

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

Paul Butcher

Posted 2011-12-05T14:44:27.150

Reputation: 221

6

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")
          ;}}

Skizz

Posted 2011-12-05T14:44:27.150

Reputation: 2 225

5

Mathematica, 50

MatrixForm@Prepend[Row/@Table[0,{n,9},{2n-1}],"*"]

Mr.Wizard

Posted 2011-12-05T14:44:27.150

Reputation: 2 481

5

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?

MrMRDubya

Posted 2011-12-05T14:44:27.150

Reputation: 171

5

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

sirchristian

Posted 2011-12-05T14:44:27.150

Reputation: 171

5

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 :(.

Rob Fox

Posted 2011-12-05T14:44:27.150

Reputation: 201

4

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.

Ante

Posted 2011-12-05T14:44:27.150

Reputation: 321

4

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

Joshua

Posted 2011-12-05T14:44:27.150

Reputation: 141

2This is 120 characters actually. – Rob Fox – 2011-12-08T13:05:17.573

4

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";}

Graham Christensen

Posted 2011-12-05T14:44:27.150

Reputation: 141

I know I'm 8 months late, but http://codegolf.stackexchange.com/a/6783/4967 :)

– Leigh – 2012-07-26T22:38:30.857

2enable short tags and save yourself 3 chars, or use the <?= and save another 5 from the "echo ". – Brombomb – 2011-12-06T20:36:20.847

4

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. :)

Weston C

Posted 2011-12-05T14:44:27.150

Reputation: 151

4

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 . . .

JoeFish

Posted 2011-12-05T14:44:27.150

Reputation: 691

4

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

Kevin Traver

Posted 2011-12-05T14:44:27.150

Reputation: 41

1This is [tag:code-golf], so please add the byte count of your submission to the header. – lirtosiast – 2015-09-29T19:25:27.097

4

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.

Phan

Posted 2011-12-05T14:44:27.150

Reputation: 41

3

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

James

Posted 2011-12-05T14:44:27.150

Reputation: 54 537

3

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

Kris

Posted 2011-12-05T14:44:27.150

Reputation: 131

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++); – Lucia – 2011-12-06T13:23:39.550

your hardcoded first line would go out of balance if you change the height of the tree tho :-( – Kris – 2011-12-06T13:50:39.230

3

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);}

Patrick

Posted 2011-12-05T14:44:27.150

Reputation: 221

3

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.)

Daniel Schneller

Posted 2011-12-05T14:44:27.150

Reputation: 131

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 = "";

– Reinis Mazeiks – 2018-02-02T00:45:03.213

3

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  

Zvezdochet

Posted 2011-12-05T14:44:27.150

Reputation: 131

2

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));}

litchie

Posted 2011-12-05T14:44:27.150

Reputation: 21

2

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.

Paul Butcher

Posted 2011-12-05T14:44:27.150

Reputation: 221

2

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 ..

SiZ

Posted 2011-12-05T14:44:27.150

Reputation: 21

1

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

James

Posted 2011-12-05T14:44:27.150

Reputation: 54 537

1

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*$_)}

mazzy

Posted 2011-12-05T14:44:27.150

Reputation: 4 832

1

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

Tobias Müller

Posted 2011-12-05T14:44:27.150

Reputation: 111

1

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

Averroes

Posted 2011-12-05T14:44:27.150

Reputation: 3 771

1

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.

stusmith

Posted 2011-12-05T14:44:27.150

Reputation: 121

1

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

Jochem

Posted 2011-12-05T14:44:27.150

Reputation: 111

1

PHP, 136 Characters


        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000


;)

Weston C

Posted 2011-12-05T14:44:27.150

Reputation: 151

1Now make the size adjustable. :) – Ilmari Karonen – 2011-12-06T21:45:28.067

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 – 2011-12-07T00:55:45.947

1

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

ICR

Posted 2011-12-05T14:44:27.150

Reputation: 211

The Main method does not need a string[] input parameter. It can be declared as: static void Main() – m0sa – 2012-03-21T19:15:01.880

@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 – 2012-03-26T14:41:28.093

Hmm, looks like my BF answer at least beats something... – Esolanging Fruit – 2016-12-08T06:38:16.903

1

Haskell, 73 characters

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

And the output:

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000

MtnViewMark

Posted 2011-12-05T14:44:27.150

Reputation: 4 779

1

Python, 64

Yet another python answer.

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

Steven Rumbalski

Posted 2011-12-05T14:44:27.150

Reputation: 1 353

1

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.

Vladimir

Posted 2011-12-05T14:44:27.150

Reputation: 129

1

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)

m0sa

Posted 2011-12-05T14:44:27.150

Reputation: 549

1

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

Armand

Posted 2011-12-05T14:44:27.150

Reputation: 499

1

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

scott

Posted 2011-12-05T14:44:27.150

Reputation: 111

Alas, there's already a shorter Ruby solution.

– Ilmari Karonen – 2011-12-10T17:43:03.940

1

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

Brad

Posted 2011-12-05T14:44:27.150

Reputation: 11

1

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

MARTIN Damien

Posted 2011-12-05T14:44:27.150

Reputation: 181

1

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.

r.e.s.

Posted 2011-12-05T14:44:27.150

Reputation: 2 872

1

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

Cristian Lupascu

Posted 2011-12-05T14:44:27.150

Reputation: 8 369

1

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

Nitin Nizhawan

Posted 2011-12-05T14:44:27.150

Reputation: 131

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. – wizzwizz4 – 2016-01-10T10:04:33.950

0

JavaScript, 108 bytes 92 bytes

i=9,n=Array(i).join(' '),s='0',a=[n+'*'];while(i--)a.push(n.substr(0,i)+s),s+='00';console.log(a.join('\n'))

edited:

i=10,n=' '.repeat(i-1),s='0',t=n+'x';for(;i--;s+='00')t+='\n'+n.substr(0,i)+s;console.log(t)

ungolfed:

i=10,n=' '.repeat(i-1),s='0',t=n+'x';

for(;i--;s+='00')t+='\n'+n.substr(0,i)+s;

console.log(t);

Hyan Christian

Posted 2011-12-05T14:44:27.150

Reputation: 1

Welcome to PPCG! Nice first post! – Rɪᴋᴇʀ – 2016-12-07T01:01:02.217

Welcome to PPCG! n='<9 spaces>' will save you a few bytes over your current setup. You can also save a few bytes by switching to a for loop, like so: for(;i--;s+='00')a.push(n.substr(0,i)+s); You can also read through the Tips for golfing in JavaScript thread for more ways to golf, if you'd like.

– ETHproductions – 2016-12-07T01:09:56.817

@ETHproductions that's very good tips, thanks – Hyan Christian – 2016-12-07T09:58:27.730

0

JavaScript, 71 bytes

for(i=z='10';i--;z+='00')console.log('        *'.slice(0,i)+z.slice(3))

This challenge seemed to be suffering from a distinct lack of super-short JavaScript answers, so I thought I'd try to make up for that. This is the shortest ES5 solution I have found thus far.

Test snippet

for(i=z='10';i--;z+='00')console.log('        *'.slice(0,i)+z.slice(3))

ETHproductions

Posted 2011-12-05T14:44:27.150

Reputation: 47 880

0

Brainf*ck, 163 bytes

This could be golfed further, but this is my first serious attempt at golfing in general, so oh well...

++++++++++[->+>+>+<<<]>>>++++++[->>++>+++<<<]>>.<<<-[>>>.<<+<-]>>>>------.++++++>+<<<<+.-[-[-<+>>+<]<[->+<]>>>..<[->.<]>>>[->+>+<<]>[-<+>]>[-<<<.>>>]<<++<<<<<<.>>]

Output:

          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000

Esolanging Fruit

Posted 2011-12-05T14:44:27.150

Reputation: 13 542

0

jQuery, 160 152 143 bytes

Well, I recognize that it's late, and that it didn't beat the other jQuery entries, but it's been a LONG time since I've done any javascript, so here goes:

$.fn.x=function(h){for(var i=1,o=" ".repeat(h-2)+"*\n";i++<h;)o+=(i==h?"0".repeat(i+(i-3)):" ".repeat(h-i)+"0".repeat(i+(i-3)))+"\n";return o};

Can be run from your browser's javascript console with $().x(10), and accepts any height parameter. Keep in mind, Chrome's console puts a quotation mark at the beginning and end of console output, so that makes the * appear out of place, but it's not.

HaLo2FrEeEk

Posted 2011-12-05T14:44:27.150

Reputation: 101

0

Kotlin, 113 bytes

{(0..9).map{print(' ')}
println('*')
(0..9).map{(it..9).map{print(' ')}
(0..it-1).map{print("00")}
println('0')}}

Beautified

{
    (0..9).map { print(' ') }
    println('*')
    (0..9).map {
        (it..9).map { print(' ') }
        (0..it-1).map { print("00") }
        println('0')
    }
}

Test

var f:()->Unit =
{(0..9).map{print(' ')}
println('*')
(0..9).map{(it..9).map{print(' ')}
(0..it-1).map{print("00")}
println('0')}}

fun main(args: Array<String>) {
    f()
}

TIO

TryItOnline

jrtapsell

Posted 2011-12-05T14:44:27.150

Reputation: 915

0

uBASIC, 63 bytes

0?Tab(9);"*":ForI=0To8:?Tab(9-I);:ForJ=0To2*I:?0;:NextJ:?:NextI

Try it online!

Taylor Scott

Posted 2011-12-05T14:44:27.150

Reputation: 6 709

0

MY-BASIC, 95 bytes

S="         *"
Print S;
For I=0 To 8
Print Left(S,9-I)d
For J=0 To 2*I
Print 0
Next
Print;
Next

Try it online!

Taylor Scott

Posted 2011-12-05T14:44:27.150

Reputation: 6 709

0

AWK, 71 bytes

{for(;$1--;)printf"%"$1-(a==0)"s%0"2*++F-3(a?"d":"s")"\n","",a++?0:"*"}

Try it online!

It seems like some simplification should be possible, but I can't find it.

NOTE: The TIO link has a few extra bytes to allow printing multiple trees.

        *
        0
       000
      00000
     0000000
    000000000
   00000000000
  0000000000000
 000000000000000
00000000000000000

Robert Benson

Posted 2011-12-05T14:44:27.150

Reputation: 1 339

0

APL (Dyalog Classic), 25 bytes

' *0'[(⊣⌿⍪+⍨)(⊖,~)∘.≤⍨⍳⎕]

Try it online!

        *         
        0         
       000        
      00000       
     0000000      
    000000000     
   00000000000    
  0000000000000   
 000000000000000  
00000000000000000 

it's resizable:

                   *                    
                   0                    
                  000                   
                 00000                  
                0000000                 
               000000000                
              00000000000               
             0000000000000              
            000000000000000             
           00000000000000000            
          0000000000000000000           
         000000000000000000000          
        00000000000000000000000         
       0000000000000000000000000        
      000000000000000000000000000       
     00000000000000000000000000000      
    0000000000000000000000000000000     
   000000000000000000000000000000000    
  00000000000000000000000000000000000   
 0000000000000000000000000000000000000  
000000000000000000000000000000000000000 

ngn

Posted 2011-12-05T14:44:27.150

Reputation: 11 449

0

Java (OpenJDK 8), 165 bytes

I saw some possible changes in the existing Java answer and thought I'd add my answer. (trims off 65 bytes, so I'm pretty proud tbh)

interface p{static void main(String[]a){String s="        ",o=s+"*";for(int i=0;i<9;i++){o+="\n"+s.substring(i);for(int j=0;j<=2*i;j++)o+=0;}System.out.println(o);}}

Try it online!

Addison Crump

Posted 2011-12-05T14:44:27.150

Reputation: 10 763

0

PHP, 69 bytes

while($i<10)printf("%".(8+$i+!$i)."s
",$i++?str_pad(0,$i*2-3,0):'*');

Run with php -nr '<code>' or try it online.


Resizable version, 76+1 bytes (run as pipe with -nR):

while($i<$argn)printf("%".($argn+$i+!$i)."s
",$i++?str_pad(0,$i*2-3,0):'*');

Titus

Posted 2011-12-05T14:44:27.150

Reputation: 13 814

0

Kotlin, 108 bytes

A few years late, but I was searching for something else and it was in my search results. Accepts a input for the rows. Fixing it to 10 rows saves 6 bytes (code below).

{n:Int->(0..n).map{if(it<1)" ".repeat(n)+"*"
else " ".repeat(n-it+1)+"0".repeat(it*2-1)}.joinToString("\n")}

Try it online!

Output: * 0 000 00000 0000000 000000000 00000000000 0000000000000 000000000000000 00000000000000000 0000000000000000000 Hardcoded with 10: {(0..10).map{if(it<1)" ".repeat(10)+"*" else " ".repeat(11-it)+"0".repeat(it*2-1)}.joinToString("\n")}

JohnWells

Posted 2011-12-05T14:44:27.150

Reputation: 611

You can to save some bytes: {n:Int->(-1..n).map{if(it<0)"".padEnd(n)+"*" else "".padEnd(n-it)+"0".repeat(it*2+1)}.joinToString("\n")} – mazzy – 2018-10-08T11:20:28.633

0

C#, Fixed height, 136 chars

class P{static void Main(){for(int i=0;i<10;i++)System.Console.WriteLine((i>0?new string('0',(i-1)*2+1):"*").PadLeft(10+(i>0?i-1:0)));}}

Formatted:

class P
{
    static void Main()
    {
        for (int i = 0; i < 10; i++)
            System.Console.WriteLine((i > 0 ? new string('0', (i - 1) * 2 + 1) : "*").PadLeft(10 + (i > 0 ? i - 1 : 0)));
    }
}

Output when run:

         *
         0
        000
       00000
      0000000
     000000000
    00000000000
   0000000000000
  000000000000000
 00000000000000000

Variable height: 165 chars

Use commandline parameter to specify height

class P{static void Main(string[]a){int h=int.Parse(a[0]);for(int i=0;i<h;i++)System.Console.WriteLine((i>0?new string('0',(i-1)*2+1):"*").PadLeft(h+(i>0?i-1:0)));}}

Formatted:

class P
{
    static void Main(string[] a)
    {
        int h = int.Parse(a[0]);
        for (int i = 0; i < h; i++)
            System.Console.WriteLine((i > 0 ? new string('0', (i - 1) * 2 + 1) : "*").PadLeft(h + (i > 0 ? i - 1 : 0)));
    }
}

Output for foo.exe 15:

              *
              0
             000
            00000
           0000000
          000000000
         00000000000
        0000000000000
       000000000000000
      00000000000000000
     0000000000000000000
    000000000000000000000
   00000000000000000000000
  0000000000000000000000000
 000000000000000000000000000

RobIII

Posted 2011-12-05T14:44:27.150

Reputation: 397

0

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

PyRulez

Posted 2011-12-05T14:44:27.150

Reputation: 6 547

0

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");}}

Wade Tandy

Posted 2011-12-05T14:44:27.150

Reputation: 101

0

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

Anders

Posted 2011-12-05T14:44:27.150

Reputation: 9

0

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.

Tommy

Posted 2011-12-05T14:44:27.150

Reputation: 821

0

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

Paolo

Posted 2011-12-05T14:44:27.150

Reputation: 696

0

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

Event_Horizon

Posted 2011-12-05T14:44:27.150

Reputation: 287

0

CSV, 133 bytes

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

        0,
       000,
      00000,
     0000000,
    000000000,
   00000000000,
  0000000000000,
 000000000000000,
00000000000000000

NRGdallas

Posted 2011-12-05T14:44:27.150

Reputation: 707

0

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

Leigh

Posted 2011-12-05T14:44:27.150

Reputation: 261

0

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*

Kazark

Posted 2011-12-05T14:44:27.150

Reputation: 289

0

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

Haile

Posted 2011-12-05T14:44:27.150

Reputation: 101