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!
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>
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 [1].
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! [2]
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 [3], 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! [4]
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
kolmogorov-complexity
[5] 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.)
" "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"*}%
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.
printf %9c\\n \* 0|sed ':x
p;s/ 0/000/;tx
d'
Prints this tree:
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
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.
Inspired by Mr.Wizard's Mathematica entry [1], 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...
(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 [2] with the latest version, but alas... [3])
[1] https://codegolf.stackexchange.com/a/4139/3191say$"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 9
s earlier in the code, which control how far from the left side of the screen the tree is indented.
(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
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.
for
. - badp
" "*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
print' '*9+'*'
for i in range(9):print' '*(9-i)+'0'*(i*2+1)
print
not a function). - Kazark
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
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")
;}}
MatrixForm@Prepend[Row/@Table[0,{n,9},{2n-1}],"*"]
/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?
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
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 :(.
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.
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
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";}
<?=
and save another 5 from the "echo ". - Brombomb
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. :)
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 . . .
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! [1]
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
[1] https://tio.run/##nVHBDoIwDL3vK54cPRjhpCczYIRGYIQNIl7VGwn/f8IxGAkhmmgPXdrXvtd2Xd89@udrGCJeIOUKSsckLyzlBP8QMMpBBdoKmZQl6rKcooZX0JQhlDqF4iK3GUNxYjDWkKIwE/Dg7UYKWWvNHQtb0L3HyIpyqJJHQrHpQWV4HHIXlVTMepP3f57obCf63BVs24Kxb54Is61WmhnXa/0nMy22lTl@k1mqPBsuV4spSSATlzD0vi1w11N1PsJTaNBg@zlXnd7CVgzDGwselect 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.
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
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);}
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.)
while (++i < c) {
-> for (s += "*";++i < c;s = "") {
, and remove the s += "*";
and the s = "";
- Reinis Mazeiks
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
17i0<esc>qqYPxr q8@qa*
Try it online [1] 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
[1] http://v.tryitonline.net/#code=MTdpMBtxcVlQeHIgcThAcWEq&input=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));}
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.
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 ..
Program (replace S,T,L with Space,Tab,Linefeed characters respectively):
SSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSTSTSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTSTSLTLSSSSSTSSSSSLTLSSSSSTSSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSSSSTTSSSSLTLSSLLL
or download the whitespace-only program text-file christmas_tree.ws [1].
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.
[1] https://sites.google.com/site/res0001/whitespace/programs/christmas_tree.wsdeclare @ int
set @=10;with t as(select space(@-1)+'*'z,1 i
union all
select space(@-i)+replicate('0',i*2-1),i+1 from t)
select top(@)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 [1].
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
EDIT: Saved 9 chars thanks to BradC!
[1] http://msdn.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx@
as the variable instead of @h
, and by dropping the AS
column keywords on z and i (although you'll still need it for table t). Also, in SQL 2008 and later you can set the value as part of the declare: declare @ int=10
- BradC
as
, but the @
var name - I didn't think that was possible. :) - Cristian Lupascu
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
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
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.
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
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
;)
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
main=mapM_ putStrLn$" *":take 9(iterate((++"00").tail)" 0")
And the output:
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
Yet another python answer.
def f(i,c='0'):print' '*(9-i)+c*(i*2+1)
f(0,'*')
map(f,range(9))
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.
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)
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
puts' '*8+'*';9.times{|a|puts' '*(8-a)+'0'*(a*2+1)}
Output:
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
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
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
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
17é0òÄlxx>òr*
Try it online! [2]
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
[1] http://github.com/DJMcMayhem/V' '*8+'*'
8..0|%{' '*$_+'0'*(17-2*$_)}
Output:
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
param($h)' '*$h+'*'
$h..0|%{' '*$_+'0'*(17-2*$_)}
Fixed height=10:
@set[= 0
@echo%[:0=*%
:0
@echo%[%
@set[=%[:~1%00
@goto:0%[:~1%
Saved 6 bytes by replacing \r\n
line terminators with \n
(still works)
P.S I'm new to golf, so I'm not sure if Removed pause
is required.@pause
, saved 7 bytes.
2020/4/30 - Abused token delimiters [
, golfed 2 bytes.
\n@pause
, since it does not change your program's output. - Jonathan Frech
↓*G↙→→⁹0
-2 bytes thanks to @Neil.
Try it online (verbose) [3] or try it online (pure) [4].
Explanation:
Print the "*"
, and move the cursor down:
Print(:Down, "*");
↓*
Draw a polygon in the shape of a triangle, with the initial arm as size 9 and using the character "0"
as filler:
Polygon(:DownRight, :Left, :Left, 9, "0");
G↙→→⁹0
Variable height through input: 14 9
bytes
[5]:
↓*G↘←←⊖θ0
-5 bytes thanks to @Neil.
Try it online (verbose) [6] or try it online (pure) [7].
Explanation:
Print the "*"
, and move the cursor down:
Print(:Down, "*");
↓*
Draw a polygon in the shape of a triangle, with the initial arm as size input-1
and using the character "0"
as filler:
Polygon(:DownRight, :Left, :Left, Decremented(q), "0");
G↘←←⊖θ0
[1] https://github.com/somebody1234/Charcoal/wiki/Tutorial↓*G↙→→⁹0
for 8 bytes. - Neil
G↗↘←⊖θ0M⊖θ↑*
to your latest linked code in your explanation? - Neil
0000<Ctrl-A><Ctrl-D><Ctrl-A><Ctrl-D><Home>0<Ctrl-Shift-R><Ctrl-D><Del><Backsp><Space>
→<Ctrl-Shift-R><Ctrl-Shift-P><Ctrl-Shift-P><Ctrl-Shift-P><Ctrl-Shift-P>
<Ctrl-Shift-P><Ctrl-Shift-P><Ctrl-Shift-P><Ctrl-D><Backsp>*
(Newlines included only for readability.)
We'll build the tree from the bottom up:
The setup
Starting with four 0
s, we CtrlA CtrlD (select all, duplicate) twice to get sixteen 0
s. We need seventeen 0
s on the bottom row, so we go Home and add another one. The cursor is now positioned right after the first 0
on the line.
The macro
CtrlShiftR starts recording a macro, which we'll use to generate each line from the one below it:
0
on the line, Del Backsp Space removes two 0
s and prepends a space0
on the lineA second CtrlShiftR ends the macro, and then CtrlShiftP seven times calls the macro repeatedly to generate the rest of the body of the tree.
The finishing touch
For the star, we need only duplicate the top row with CtrlD, remove the 0
with Backsp, and replace it with a *
.
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
[1] https://notepad-plus-plus.orgsay " "*8+"*"
X's0
while 9-X
let Y be 8-X
say " "*Y+0+"0"*X*2
let X be+1
Try it here [2] (Code will need to be pasted in)
[1] https://codewithrockstar.com/⁶ẋ8⁾*¶9µ>þa⁶UŒBY
Try it online! [2]
This is my first time golfing in Jelly; I'm sure this could be golfed further. Advice welcome. :^)
⁶ Space character
ẋ8 Repeated 8 times
Since this niladic chain doesn't connect to anything, just output it
⁾*¶ Two-character string containing * and newline
Since this niladic chain doesn't connect to anything, just output it
9µ Apply the following monadic chain to a starting value of 9:
>þ Make a 9x9 table, where each entry is 1 if the column number is
greater than the row number, 0 if not
a⁶ Logical AND with space (replaces the 1's with spaces)
U Reverse each row
ŒB Bounce, mirroring each row to the right
Y Join with newlines
[1] https://github.com/DennisMitchell/jelly9\*꘍₀(,9n-\0n›*꘍øm
Try it Online! [2]
Fairly well golfed.
9 # 9
\* # '*'
꘍ # ' ' * 9 + '*'
₀( # 10 times
, # output
9n- # 9 - (iteration number)
\0 # String '0'
n› # iteration number + 1
* # That many 0s
꘍ # (9 - (iteration number)) spaces + 0s
øm # Palindromised
Tree:
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
[1] https://github.com/Lyxal/Vyxaln=-1
exec"print' '*(8-n/2%n),n*'0'or'*';n+=2;"*10
Try it online! [2]
n=-1
while n<19:print(f"{n*'0'or'*':^19}");n+=2
Try it online! [4]
[1] https://docs.python.org/2/C
, 9 bytes17~∷\0*×p
Try it Online! [2]
17~ # the range 1..17 filtered by
∷ # is odd
\0* # "0" repeated n times for n in those odd nums
×p # with an asterisk prepended
# C flag joins by newlines and centers output
[1] https://github.com/Vyxal/VyxalTakes 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");}}
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
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.
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
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);
*
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
0000000000000000000
000000000000000000000
00000000000000000000000
0000000000000000000000000
000000000000000000000000000
00000000000000000000000000000
0000000000000000000000000000000
000000000000000000000000000000000
00000000000000000000000000000000000
0000000000000000000000000000000000000
000000000000000000000000000000000000000
00000000000000000000000000000000000000000
00000
00000
00000
Thought I would Cheat Just a little on this one for a few laughs :)
0,
000,
00000,
0000000,
000000000,
00000000000,
0000000000000,
000000000000000,
00000000000000000
<?=($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
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
Using mapping to reduce number of characters:
map b a0^[k
map c a ^[
norm8ca*^[9o^[17bc15b2c13b3c11b4c9b5c7b6c5b7c3b8ca0
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
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.-
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*
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
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
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
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
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);
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
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.
for(i=z='10';i--;z+='00')console.log(' *'.slice(0,i)+z.slice(3))
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
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.
{(0..9).map{print(' ')}
println('*')
(0..9).map{(it..9).map{print(' ')}
(0..it-1).map{print("00")}
println('0')}}
{
(0..9).map { print(' ') }
println('*')
(0..9).map {
(it..9).map { print(' ') }
(0..it-1).map { print("00") }
println('0')
}
}
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()
}
TryItOnline [2]
[1] https://kotlinlang.org0?Tab(9);"*":ForI=0To8:?Tab(9-I);:ForJ=0To2*I:?0;:NextJ:?:NextI
Try it online! [2]
[1] https://github.com/EtchedPixels/ubasicS=" *"
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! [2]
[1] https://github.com/paladin-t/my_basic{for(;$1--;)printf"%"$1-(a==0)"s%0"2*++F-3(a?"d":"s")"\n","",a++?0:"*"}
Try it online! [2]
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
[1] https://www.gnu.org/software/gawk/manual/gawk.html' *0'[(⊣⌿⍪+⍨)(⊖,~)∘.≤⍨⍳⎕]
Try it online! [2]
*
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
[1] https://www.dyalog.com/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! [2]
[1] http://openjdk.java.net/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
[1].
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):'*');
[1] http://sandbox.onlinephpfunctions.com/code/6a9ea80b14045c1fc01af98cf45511ff39ff2266A 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! [2]
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")}
{n:Int->(-1..n).map{if(it<0)"".padEnd(n)+"*" else "".padEnd(n-it)+"0".repeat(it*2+1)}.joinToString("\n")}
- mazzy
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).
Try it online! [2]
[1] http://erlang.org/doc/man/escript.html¾17ÅÉ×'*š.c
Try it online. [3]
Variable height through input: 12 11
bytes
[4]:
ηÍÅÉ×'*š.c
Try it online. [5]
Explanation:
¾ # 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
[1] https://github.com/Adriandmen/05AB1E/wiki/Commandsh=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.
-R
[2], AÇçT êÃh* û
Test it [4]
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
[1] https://github.com/ETHproductions/japt/i/ /i*/> /
i0\/ \\0\/a\\a\/\/a\\a\/000\/>//>//>i
Try it online! [2]
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.