27
\$\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\$

82 Answers 82

1 2
3
0
\$\begingroup\$

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*
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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

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
| improve this answer | |
\$\endgroup\$
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
| improve this answer | |
\$\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))

| improve this answer | |
\$\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);
| improve this answer | |
\$\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
| improve this answer | |
\$\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

| improve this answer | |
\$\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
| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

uBASIC, 63 bytes

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

Try it online!

| improve this answer | |
\$\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!

| improve this answer | |
\$\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
| improve this answer | |
\$\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 
| improve this answer | |
\$\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!

| improve this answer | |
\$\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):'*');
| improve this answer | |
\$\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")}

| improve this answer | |
\$\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
0
\$\begingroup\$

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

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Rockstar, 72 bytes

say " "*8+"*"
X's0
while 9-X
let Y be 8-X
say " "*Y+0+"0"*X*2
let X be+1

Try it here (Code will need to be pasted in)

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Japt -R, 12 bytes

AoçT h* mê û

Test it

AoçT h* mê û     :(Remove A to input the height instead)
A                :10
 o               :Range [0,A) (or [0,input))
  ç              :For each repeat
   T             :  0
     h*          :Replace the first element with "*"
        m        :Map
         ê       :  Palindromise
           û     :Centre pad with spaces to the length of the longest
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

05AB1E, fixed height: 11 bytes

¾17ÅÉ×'*š.c

Try it online.

Variable height through input: 12 11 bytes:

ηÍÅÉ×'*š.c

Try it online.

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
| improve this answer | |
\$\endgroup\$
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.