26
\$\begingroup\$

The Challenge

Print a nice Christmas tree with it's own star at the top using the shortest code possible. The tree star is an asterisk (*) and the tree body is made out of 0 The tree must be 10 rows high. Every row should be properly indented in the way that the previous row are centered over the next one. Any given row must have 2 more 0s than the previous, except for the first one that is the star and the second, which has only one 0. The result is something like this:

          *
          0
         000
        00000
       0000000
      000000000
     00000000000
    0000000000000
   000000000000000
  00000000000000000

Tie break for resizable height trees without software changes (except changing height parameter)

Please, paste the resulting tree of your code too!


Leaderboard

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

\$\endgroup\$

74 Answers 74

1 2 3
0
\$\begingroup\$

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

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

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

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);
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! Nice first post! \$\endgroup\$ – Rɪᴋᴇʀ Dec 7 '16 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 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. \$\endgroup\$ – ETHproductions Dec 7 '16 at 1:09
  • \$\begingroup\$ @ETHproductions that's very good tips, thanks \$\endgroup\$ – Hyan Christian Dec 7 '16 at 9:58
0
\$\begingroup\$

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

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

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

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

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.

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

uBASIC, 63 bytes

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

Try it online!

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

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!

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

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

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

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!

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

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):'*');
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
  • \$\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 Oct 8 '18 at 11:20
1 2 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.