92
\$\begingroup\$

Given a number N, how can I print out a Christmas tree of height N using the least number of code characters? N is assumed constrained to a minimum value of 3, and a maximum value of 30 (bounds and error checking are not necessary). N is given as the one and only command line argument to your program or script.

All languages appreciated, if you see a language already implemented and you can make it shorter, edit if possible - comment otherwise and hope someone cleans up the mess. Include newlines and White Spaces for clarity, but don't include them in the character count.

A Christmas tree is generated as such, with its "trunk" consisting of only a centered "*"

N = 3:

   *
  ***
 *****
   *

N = 4:

    *
   ***
  *****
 *******
    *

N = 5:

     *
    ***
   *****
  *******
 *********
     *

N defines the height of the branches not including the one line trunk.

Merry Christmas PPCG!

\$\endgroup\$

103 Answers 103

1
\$\begingroup\$

This is my first experience with code golf. So advices are welcome :)

C: 170 chars:

int main(){
    int n,m=1,x;
    scanf("%d",&n);x=2*n-1;
    for(;m<x*n+n+2;m++)
        printf("%c",m==x*n|m==x*n+n+1?42:m==x*n+1?10:m>x*n?32:!(m%(2*n-1))?10:!(m%x<n-m/x)&m%x<m/x+n+1?42:32);
}
\$\endgroup\$
1
\$\begingroup\$

It's in PHP.

<center><?$t=$_GET[1]*2-$i=1;while($i<=$t){echo str_repeat('*',$i).'<br>';$i+=2;}echo'*'?><center>

Total characters(with spaces):98 Total characters(with no spaces):97 Bytes:98

\$\endgroup\$
1
\$\begingroup\$

I did not see a solution using R. The code below may not be efficient, but it seems to work (170 characters with spaces if all code placed on one line):

for(i in 1:4){ cat( paste( paste(rep(' ', (3-(i-1))), collapse=''), 
                           paste(rep('*', (2*i-1)),   collapse=''), collapse=''),  
               sep='\n'); if(i==4) cat('    *    ', sep='\n')}


    *
   ***
  *****
 *******
    *
\$\endgroup\$
1
\$\begingroup\$

Javascript, 89

i=4
c=t=""
while(i){o=c,j=(i--+1)*2-3
while(j--)o+="*"
t=o+"\n"+t
c+=" "}console.log(t+o)

Javascript 81

o=s=''
for(a=3;a--;){l=s+=' '
for(k=a*2+1;k--;)l+='*'
o=l+'\n'+o}console.log(o+l)
\$\endgroup\$
1
\$\begingroup\$

><>: 136 chars

This one's not going to win, but because Christmas is coming again, I thought fish needed a Christmas tree too! (pun intended)

1-:&1$>:> :1(?!v~$:> :1(?!vv
        ^-1o" "<   ^-1o"*"<>~2+$1-:0(?!v~~&ao>" "o1-v
      ^                              oa<;o"*"^!?(1: <

It can be run as follows with the standard interpreter:

./fish.py christmas.fish -v 5

... for N=5. (If the file is called christmas.fish :P) In this way, one prepopulates the stack with the value 5. This is the closest I could get to a command-line argument.

\$\endgroup\$
1
\$\begingroup\$

python-3x:

N = int(input())
print(' '*N+'\n','\n'.join(['\t'+' '*(N-i)+'*'*(i*2+1) for i in range(N)]) + '\n', ' '*(N+3)+'*'+'\n')

result:-

enter N value
3
   *
  ***
 *****
   *



 4
        *
       ***
      *****
     *******
        *

9
             *
            ***
           *****
          *******
         *********
        ***********
       *************
      ***************
     *****************
             *
\$\endgroup\$
  • 1
    \$\begingroup\$ You skipped both the beginning “Given a number N” and the end “with its ‘trunk’ consisting of only a centered ‘*’” of requirement. \$\endgroup\$ – manatwork Jun 17 '15 at 15:25
  • \$\begingroup\$ I corrected to give user N value and * as trunk in the end \$\endgroup\$ – Praneeth Jun 17 '15 at 17:26
  • 2
    \$\begingroup\$ Welcome to PPCG! The point of challenges like this one is to provide a solution in as few bytes as possible, so you should include in the title how long it is. (I'd recommend pasting it into this byte counter.) Speaking of which, you could shave off 25 bytes by removing the print statement at the beginning and removing the spaces around the = sign. \$\endgroup\$ – M. I. Wright Jun 17 '15 at 22:40
  • \$\begingroup\$ Ok, but this is not Python 2.7 anymore, but Python 3. ;) The remaining issue is that your code generates one size smaller tree than specified. \$\endgroup\$ – manatwork Jun 18 '15 at 14:14
  • \$\begingroup\$ I mentioned it as python-2.7 because in my systems library I have python-2.7 and in my virtualenvironment I have python 3.4. When I execute python 2.7 in the editor I get errors for example if I try end=' ' in the print function if I want to print anything in single line. I import from future to enable print functions which are active in python 3.x versions. Also I have made minor change to represent correct size of tree. \$\endgroup\$ – Praneeth Jun 18 '15 at 15:11
1
\$\begingroup\$

JavaScript, 110 characters (2 relevant spaces)

function p(l)
{
    o=''
    for(c=0; c<=n+l; c++)
      o += c < n - l ? ' ' : '*'
    print(o)
}

n = parseInt(arguments[0])

for(l = 0; l < n; l++)
  p(l)
p(0)

Ran using spidermonkey. $ smjs christmas_tree.js 4

For Javascript Console 105

function p(l){o='';for(c=0;c<=n+l;)o+=c++<n-l?' ':'*';console.log(o)}n=+prompt();for(l=0;l<n;)p(l++);p(0)
\$\endgroup\$
1
\$\begingroup\$

Scala, 73 chars

val n=args(0).toInt
(1 to n):+1 foreach(i=>println(" "*(n-i)+"*"*(2*i-1)))

run as

golf.scala 10
\$\endgroup\$
  • \$\begingroup\$ Wait, does that display the trunk? \$\endgroup\$ – Johannes Kuhn Dec 12 '13 at 19:56
  • \$\begingroup\$ yes, :+1 would do that \$\endgroup\$ – prashanth Dec 12 '13 at 20:05
1
\$\begingroup\$

Python 2 - 62 Bytes:

i,x=input()*2,1
exec"print('*'*(x%i)).center(i);x+=2;"*(i/2+1)

Multiplying the input by two saves a byte because of the need for extra brackets.
There may be a way to further golf the operations.

\$\endgroup\$
1
\$\begingroup\$

Japt, 11 bytes

õ_ç* êÃp* û

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 39 bytes

{say " "x$^a-$_,\*x$_*2-1 for 1...$a,1}

Try it online!

It's one of those questions, where it's easier to just print the lines in the code block.

Explanation:

{say " "x$^a-$_,\*x$_*2-1 for 1...$a,1}
{                                     }   # Anonymous code block
                          for 1...$a,1    # Loop over 1 to n and 1 again
 say                                      # Print
     " "x$^a-$_                           # Leading spaces
               ,\*x$_*2-1                 # And then the amount of asterisks
\$\endgroup\$
1
\$\begingroup\$

Japt -R, 11 bytes

ÇÑÄ î*Ãp* û

Try it

Ç               :Map the range [0,input)
 Ñ              :  Multiply by 2
  Ä             :  Add 1
    î*          :  Repeat * that many times
      Ã         :End map
       p*       :Push a *
          û     :Centre pad each element with spaces to the length of the longest
                :Implicitly join with newlines
\$\endgroup\$
1
\$\begingroup\$

Lua, 100 99 bytes

p,r,n=io.write,('').rep,arg[1]for i=0,n do p(r(' ',n-i+1),r('*',i*2+1),'\n')end p(r(' ',n+1),'*\n')

Try it online!

Another Lua version, a little shorter.

\$\endgroup\$
  • \$\begingroup\$ Thanks! Good catch! \$\endgroup\$ – cyclaminist Dec 23 '18 at 11:49
1
\$\begingroup\$

PHP, 79 bytes

while($argn)echo$r[]=str_pad("
",1+$argn--).str_pad("",++$n*2-1,"*");echo$r[0];

Run as pipe with -nR or try it online.

\$\endgroup\$
  • \$\begingroup\$ Save 2 bytes using variable variables: Try it online! \$\endgroup\$ – Night2 Oct 13 at 13:50
1
\$\begingroup\$

Zsh, 77 64 bytes

Since all these old questions are now open, I think the oldest q. on codegolf.se needs a zsh answer!
Try it Online!

s=*;for ((;i<$1;))printf %$[$1+i++]s\\n $s&&s+=**
printf %$1s \*

Hat-tip to Alastair from Boxing Day 2008
NB: Putting the printf stuff in a function is no advantage...
NB2: original for 77 bytes.. saved 12 bytes by eliminating quotes, braces, trailing newline

\$\endgroup\$
1
\$\begingroup\$

Poetic, 547 bytes

the triangle trees
a december i loved
o,i placed a fun christmasy thing
i know i am hoping on a santa,a gift,cookie plates,or bag o dolls
i know i am choosing my toy to expect of him,Mr.Claus
i say,Mr,i think i may ask nicely
we are nice people,we are
o,under the tree i go crazy as i glance at the a-b-c puzzle we got
a thing on Xmas i am happy to be toying with
o,i found it!for a moment,i shouted thanks
a gift i am having as we enjoy a holiday feast
and now i sleep
oh,here i am,silent as i could
i quickly awaken
i then go to locate a present

Try it online!

Translated from a version by Daniel Cristofani, but optimized specifically for program length in Poetic (more groups of > than <, more groups of + than -, etc).

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

First try in LUA

f=string.rep p=print function t(N) for i=0,N do s=f(" ",N-i) p(s..f("+",2*i-1)..s) end p(f(" ",N-1).."+"..f(" ",N-1)) end t(arg[1])

After selecting all of it scite tells me these are 131 chars

For clarities sake without optimizing away the \n etc:

f=string.rep 
p=print 
function t(N) 
 for i=0,N do 
   s=f(" ",N-i)
   p(s..f("+",2*i-1)..s)
 end 
  p(f(" ",N-1).."+"..f(" ",N-1)) 
end 
t(arg[1])

For the python version by ΤΖΩΤΖΙΟΥ I get shown 115 chars... Hrm, some more things to optimize

\$\endgroup\$
  • 1
    \$\begingroup\$ Note: all insignificant/irrelevant whitespace should be ignored, as per the question specifications. So, any beautifying/syntax-needed whitespace doesn't count, but a " " literal does count. So your fully expanded version has 119 chars (3 significant spaces) \$\endgroup\$ – tzot Dec 25 '08 at 20:06
0
\$\begingroup\$

Scala, 97 chars

This one gets n from command line.

Thanks to ΤΖΩΤΖΙΟΥ for the * operator

val n=args(0).toInt*2
(1.until(n,2))foreach{i=>println(" "*(n-i)+"* "*i)}
println (" "*(n-1) + "*")
\$\endgroup\$
0
\$\begingroup\$

Language: Erlang, Char count: 151

A little bit shorter Erlang version:

-module(x).
-export([t/1]).
t(N)->[H|_]=T=t(N,1),io:format([T,H]).
t(0,_)->[];t(N,M)->[[d(N,32),d(M,42),10]|t(N-1,M+2)].
d(N,C)->lists:duplicate(N,C).

When should run with command line argument

-module(x).
-export([t/1]).
t([N])->[H|_]=T=t(list_to_integer(N),1),io:format([T,H]),init:stop().
t(0,_)->[];t(N,M)->[[d(N,32),d(M,42),10]|t(N-1,M+2)].
d(N,C)->lists:duplicate(N,C).

Invocation:

$ erl -noshell -noinput -run x t 11
           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
           *
\$\endgroup\$
0
\$\begingroup\$

Rhino Javascript shell: 117 chars minified

t=['*'];
for(i=1;i<arguments[0];++i)
{
  s='*'+t[i-1]+'*';
  for(j in t) 
    t[j]=' '+t[j];
  t[i]=s;
}
t[i]=t[0];print(t.join('\n'));

minified:

t=['*'];for(i=1;i<arguments[0];++i){s='*'+t[i-1]+'*';for(j in t) t[j]=' '+t[j];t[i]=s;}t[i]=t[0];print(t.join('\n'));

results:

c:\>java -jar C:\appl\Java\rhino1_7R1\js.jar c:/tmp/Xtree.js 10
         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************
         *
\$\endgroup\$
0
\$\begingroup\$

Language: FoxPro 2.x for DOS (should work with Clipper too), Char count: 62

para n
for h=1 to n
?spac(n-h)+repl('*',2*h-1)
endf
?spac(n-1)+'*'
\$\endgroup\$
0
\$\begingroup\$

Language: Euphoria 147 chars (9 relevant spaces):

include get.e
object
    a = command_line(), 
    t = 42
a = value( a[3] )
a = a[2]
for i = 1 to a do
    puts(1, repeat( 32, a - i ) & t & 10)
    t &= "**"
end for
puts(1, repeat( 32, a - 1 ) & 42 & 10 )

With only relevant whitespace:

include get.e
object a=command_line(),t=42a=value(a[3])a=a[2]for i=1to a do puts(1,repeat(32,a-i)&t&10)t&="**"end for puts(1,repeat(32,a-1)&42&10)
\$\endgroup\$
0
\$\begingroup\$

Language C# in verbosity

using System;

namespace ChristmasTree
{
    class Program
    {
        static void Main( string[] args )
        {

            var buildATree = new BuildATree( int.Parse( args[0] ) );

            Console.WriteLine( buildATree.MakeTree() );

            Console.ReadLine();
        }
    }
}


using System.Text;

namespace ChristmasTree
{
    public class BuildATree
    {
        private int TreeHeight
        {
            get;
            set;
        }

        public BuildATree()
            : this( 3 )
        {}

        public BuildATree( int treeHeight )
        {
            this.TreeHeight = treeHeight;

            if( treeHeight > 30 )
                this.TreeHeight = 30;
        }

        public string MakeTree()
        {
            StringBuilder sb = new StringBuilder();

            for( int i = 0; i < this.TreeHeight; i++ )
            {
                sb.AppendLine( 
                    new string( ' ', this.TreeHeight - i - 1 ) 
                    + new string( '*', i * 2 + 1 ) );
            }

            sb.AppendLine( new string( ' ', this.TreeHeight-1 ) + "*" );

            return sb.ToString();
        }
    }
}
\$\endgroup\$
0
\$\begingroup\$

Excessively long version in J (97 chars)

t=:3 :0
d=:0
k=:''
while.d<y
do.
k=:k,((d{((y-1)+>:i.y))$!.'*'((d{((|.i.y)))$,' ')),LF
d=:d+1
end.k,y$k
)

Run it this way:

t N

where N is tree height.

And Merry Xmas (a bit late).

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

in c++, the shortest and the fastest way "i think" :)

void tree(int c, char* o)
{
#define _(p,x) t=p;while(t--)*o++=x
    if(o&&c>0)
    {
    	int m=c+1,t;
    	do
    	{
    		_(c,' ');
    		_((m-c)*2-1,'*');
    		_(c,' ');
    		*o++='\n';
    	}while(--c);
    	_(m-1,' ');
    	*o++= '*';
    	*o++='\n';
    	*o=0;
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    char t[1024];
    tree(5, t);
    printf("%s", t);
}
\$\endgroup\$
0
\$\begingroup\$

C# 3.0

using System;
using System.Linq;
class Program
{
    static void Main(string[] a)
    {
        int n = int.Parse(a[0]);
        Console.WriteLine(Enumerable.Range(1, n).Concat(new int[] { 1 })
            .Select(x => new string('*', x * 2 - 1).PadLeft(x + n))
            .Aggregate((x, y) => x + "\n" + y));
    }
}

158 characters:

int n=int.Parse(a[0]);Console.WriteLine(Enumerable.Range(1,n).Concat(new int[]{1}).Select(x=>new string('*',x*2-1).PadLeft(x+n)).Aggregate((x,y)=>x+"\n"+y));
\$\endgroup\$
0
\$\begingroup\$

Here's a Ruby Newbie (ha! It rhymes!) with his first working solution:

Ruby 164 characters (of readable code)

n=gets.to_i-1
(0..n).each do |j|  
    (n-j).times do 
        print " "
    end 
    (1+j*2).times do
        print "*" 
    end
    print "\n"
end
n.times do 
    print " "
end
print "*"
\$\endgroup\$
0
\$\begingroup\$

C++

#include<iostream>

using namespace std;

int main(int a,char**c)
{
    int h = atoi(c[1]);
    for(int i=0; i<h; i++)
    {
        cout << string(h-i, ' ') << string(i*2+1, '*') << endl;
    }
    cout << string(h, ' ') << '*' << endl;
}

golfed to 188 char

#include<iostream>    
using namespace std;
#define s string
int main(int a,char**c){int h=atoi(c[1]);for(int i=0;i<h;i++){cout<<s(h-i,' ')<<s(i*2+1,'*')<<endl;}cout<<s(h,' ')<<'*'<<endl;}
\$\endgroup\$
0
\$\begingroup\$

GolfScript, 34 characters

Another GolfScript entry:

~:x,-1%[x(]+{." "*x@- 2*("*"*n.},;

Explanation:

~:x                   #read input, store into x
,                     #create array [0,1,2,...,x-1]
-1%                   #reverse it
[x(]+                 #append x-1 to the array
{." "*x@- 2*("*"*n.}, #map each element in array to this block, outputs each line
;                     #remove results of map from stack

The block does:

{.                    #duplicate value given by map (stack is now: i i)
" "*                  #push " ", times it by i (stack now: i "   ") 
x                     #push x, stack is: (i "   " x), and bring i
@                     #bring i to the front (stack is: "   " x i)
- 2*(                 #pop x,i, push ((x-i)*2-1)
"*"*                  #print that many *'s
n.}                   #print newline, duplicate it so the map doesn't kill it
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 137 bytes

function k(a){var b="";for(i=0;i<a;i++){for(j=0;j<a*2;j++)b+=j>a-2-i
&&j<a+i?"*":" ";b+="\n"}for(i=0;i<a*2;i++)b+=i==a-1?"*":" ";return b}

Test case (formatting disorder is due to the first " marking a string):

k(3)

"  *   
 ***  
***** 
  *   "
\$\endgroup\$

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.