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>
-
3\$\begingroup\$ 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 \$\endgroup\$Hasturkun– Hasturkun2011年12月05日 16:39:56 +00:00Commented Dec 5, 2011 at 16:39
88 Answers 88
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.
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
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
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
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
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*
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
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
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
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))
-
\$\begingroup\$ I golfed off 2 bytes: Try it online! \$\endgroup\$Andrew Bayly– Andrew Bayly2024年08月05日 19:00:17 +00:00Commented Aug 5, 2024 at 19:00
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);
-
\$\begingroup\$ Welcome to PPCG! Nice first post! \$\endgroup\$Riker– Riker2016年12月07日 01:01:02 +00:00Commented Dec 7, 2016 at 1:01
-
\$\begingroup\$ 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 aforloop, 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. \$\endgroup\$ETHproductions– ETHproductions2016年12月07日 01:09:56 +00:00Commented Dec 7, 2016 at 1:09
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
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
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
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.
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
AWK, 71 bytes
{for(;1ドル--;)printf"%"1ドル-(a==0)"s%0"2*++F-3(a?"d":"s")"\n","",a++?0:"*"}
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
APL (Dyalog Classic), 25 bytes
' *0'[(⊣⌿⍪+⍨)(⊖,~)∘.≤⍨⍳⎕]
*
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
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);}}
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):'*');
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")}
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")}
-
\$\begingroup\$ 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")}\$\endgroup\$mazzy– mazzy2018年10月08日 11:20:28 +00:00Commented Oct 8, 2018 at 11:20
Erlang (escript), 134 bytes
The tree is resizable.
r(-1,_)->"";r(X,Y)->lists:duplicate(X," ")++lists:duplicate(Y,"0")++"\n"++r(X-1,Y+2).
t(X)->lists:duplicate(X-1," ")++"*\n"++r(X-1,1).
C, 128
h=10;y,w,i,j;main(){for(y=-1;y<h;y++){w=1+max(y,0)*2;i=((h*2)-w)/2;for(j=0;j<i+w;j+1)printf(j<i?" ":y+1?"0":"*");printf("\n");}}
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
0000000000000000000
h is the tree's height without the star.
05AB1E, fixed height: 11 bytes
×ばつ'*š.c
Variable height through input: (削除) 12 (削除ここまで) 11 bytes :
×ばつ'*š.c
Explanation:
3⁄4 # Push 0 (push the counter_variable, which is 0 by default)
17ÅÉ # Push a list of the positive odd numbers <= 17: [1,3,5,7,9,11,13,15,17]
×ばつ # Repeat the 0 that many times as string:
# ["0", "000", "00000", ..., "00000000000000000"]
'*š '# Prepend a "*": ["*", "0", "000", "00000", ..., "00000000000000000"]
.c # Centralize each line by padding with leading spaces
# (which also implicitly joins a list by newlines at the same time)
# (after which it is output implicitly as result)
Î # Push 0 and the input-integer
· # Double the input
Í # Decrease it by 2
×ばつ'*š.c '# Same as above
///, 57 bytes
/i/ /i*/> /
i0\/ \0円\/a\\a\/\/a\\a\/000\/>//>//>i
Normally I would have another replacement for the escaped "/" in the loop bit, but it happens to be the same length without so why not.
Change the number of spaces in the first line, after the /i/. Technically, there is one less space that the 'size' but size 0, 1 etc aren't defined so I don't think it matters.
Japt -R, (削除) 12 (削除ここまで) 11 bytes
AÇçT êÃh* û
AÇçT êÃh* û :(Remove A to input the height instead)
A :10
Ç :Map the range [0,A) (or [0,input))
ç : Repeat
T : 0
ê : Palindromise
à :End map
h* :Replace the first element with "*"
û :Centre pad with spaces to the length of the longest
:Implicit output joined with newlines
brainfuck, 138 bytes
++++++++[->++++>+++++>++++++>+>+>+<<<<<<]>>++>>++>+<<<<........>.>>>>>>+<<<[-<.>>[->+<<<<<<.>>>>>]->[-<+>]>[->+<<<<<<.>>>>>]++>[-<+>]<<<<]
output:
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
ungolfed:
++++++++
[->++++>+++++>++++++>+>+>+<<<<<<]
>>++>>++>+
<<<<........>.>>>
>>>+<<<
[-
<.>
>
[-
>+
<<<<<<.
>>>>>
]
->
[-
<+>
]
>
[-
>+
<<<<<<.
>>>>>
]
++>
[-
<+>
]
<<<<
]
Explore related questions
See similar questions with these tags.