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

migrated from stackoverflow.com Dec 10 '11 at 22:16

This question came from our site for professional and enthusiast programmers.

103 Answers 103

2
\$\begingroup\$

PHP, 111 chars

(The very last char should be a newline.)

<?php $n=$argv[1];for($r='str_repeat';$i<$n;$i++)echo $r(' ',$n-$i).$r('*',$i*2+1)."\n";echo $r(' ',$n).'*' ?>

Readable version:

<?php

$n = $argv[1];

for ($r = 'str_repeat'; $i < $n; $i++)
    echo $r(' ', $n - $i) . $r('*' , $i * 2 + 1) . "\n";

echo $r(' ', $n) . '*'

?>
\$\endgroup\$
  • \$\begingroup\$ You can save several characters by building the string, then echoing it. I think. Try that out. \$\endgroup\$ – strager Dec 26 '08 at 0:10
  • \$\begingroup\$ Good idea, but I tried it and it only makes it longer. '$t.=(...)' is only one char shorter than 'echo (...)', and then you'd have to 'echo $t' at the end as well. \$\endgroup\$ – Jeremy Ruten Dec 26 '08 at 0:19
  • \$\begingroup\$ Shortened it by 4 chars by removing the '$i = 0;' first part of the for statement. PHP assumes that nonexistent variables used in an integer context are 0 already! :P \$\endgroup\$ – Jeremy Ruten Dec 26 '08 at 0:24
  • \$\begingroup\$ Saved a char by putting $r=.. inside the for. Also, I say newline characters should be one byte, not two. =] \$\endgroup\$ – strager Dec 26 '08 at 0:46
  • \$\begingroup\$ Yeah I just realized I miscounted by one because I counted using the column number in my text editor. I use linux so the newline char is one byte. \$\endgroup\$ – Jeremy Ruten Dec 26 '08 at 0:53
2
\$\begingroup\$

Windows Batch File

Windows batch files have poor support for string operations: they can concatename, extract and replace strings, but generation of arbitrary-length strings according to a certain pattern AFAIK can only be done via loops. This is how Zach Scrivena's solution works.

However, one can notice that the N+1-th tree line can be generated from the N-th line by cutting one leading space off and adding two traling asterisks, which pretty much simplifies the task. Also, the tree truck repeats the tree top so we can re-use that string to get rid of a few extra loops. So, here's my batch file that uses these two tricks (165 characters):

@echo off
setlocal enableextensions enabledelayedexpansion
set s=
for /l %%i in (1,1,%1)do set s= !s!
set t=!s!*
for /l %%i in (1,1,%1)do echo !t!&set t=!t:~1!**
echo %s%*

Assuming that echo is already off and command extensions and delayed variable expansion are on, we can drop the first two lines and shorten the code down to 108 characters.

Usage:

> xmastree.bat 7 & pause
       * 
      *** 
     ***** 
    ******* 
   ********* 
  *********** 
 ************* 
       *
\$\endgroup\$
2
\$\begingroup\$

C# - Recursion

using System;

class A
{
    static string f(int n, int r)
    {
        return "\n".PadLeft(2 * r, '*').PadLeft(n + r) 
            + (r < n ? f(n, ++r) : "*".PadLeft(n));
    }

    static void Main(string[] a)
    {
        Console.WriteLine(f(int.Parse(a[0]), 1));
    }
}

177 chars (not as short the other C# method posted, but a different way of doing it).

\$\endgroup\$
2
\$\begingroup\$

Haskell - 105 95 characters - 3 Relevant spaces

Improved on the other Haskell solution (https://codegolf.stackexchange.com/a/4267/7353) by 2 12 strokes.

  • Updated take x$cycle "*" into replicate x '*'
  • Removed unnecessary brackets

Updated version:

r=replicate;main=(\x->mapM_ putStrLn[r(x-l)' '++r(l+l-1)'*'|l<-[1..x]++[1]])=<<(readLn::IO Int)

Previous version:

c=cycle;main=(\x->mapM_ putStrLn[(take(x-l)$c" ")++(take(l+l-1)$c"*")|l<-[1..x]++[1]])=<<(readLn::IO Int)

Readable (updated) version:

main=(\ size->
          mapM_
               putStrLn
               [replicate (size - count) ' ' ++ replicate (count + count - 1) '*' | count <- [1..size] ++ [1]]
     ) =<< ( readLn :: IO Int )

Haskell is such an elegant language.

\$\endgroup\$
2
\$\begingroup\$

K 33

q)k)f:{{(|:'x),'1_'x}x$(1+(!x),0)#'"*"}
q)f 4
"   *   "
"  ***  "
" ***** "
"*******"
"   *   "
\$\endgroup\$
2
\$\begingroup\$

Python - 104 / 94 characters

Alright, so I have two solutions here. One of them is, I guess, a bit "trickier", placing all of the code on one line, while the other solution is actually shorter.

import sys
c=int(sys.argv[1])
for i in range(c+2):print" "*(c-1)+"*"if i==c+1 else" "*(c-i)+"*"*(2*i-1)

That's the 104-char version. Who said python is always readable? It doesn't use any "tricks" though, which is a plus, I guess? If we split the if/else statement onto a seperate line like so:

import sys
c=int(sys.argv[1])
for i in range(c+1):print" "*(c-i)+"*"*(2*i-1)
print" "*(c-1)+"*"

...this is much neater and is actually a few characters shorter.

\$\endgroup\$
2
\$\begingroup\$

J, 24

Works akin to the accepted answer in that you include the parameter in the source code. Expressing it as a proper function would be slightly longer. Uses a different approach than the accepted answer.

' *'#~(>:@+:,.~#-])0,~i.

E.g.

   ' *' #~ (>:@+: ,.~ #-]) 0 ,~ i.5
    *    
   ***   
  *****  
 ******* 
*********
    *    

As a function (27):

#&' *'@(>:@+:,.~#-])@,&0@i.
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 58 bytes

f=(n,s=`*
`,l)=>n?(k=' '.repeat(--n)+s)+f(n,'**'+s,l||k):l

Demo

f=(n,s=`*
`,l)=>n?(k=' '.repeat(--n)+s)+f(n,'**'+s,l||k):l

console.log(f(7))

\$\endgroup\$
2
\$\begingroup\$

05AB1E, 9 bytes

LĆ'*×j€û»

Try it online or verify all Christmas trees in the range [3, 30].

€û» can alternatively be ».º for the same byte-count.

Explanation:

L            # Create a list in the range [1, (implicit) input]
             #  i.e. 3 → [1,2,3]
 Ć           # Enclose; adding the first item (the 1) also add the end of the list
             #  i.e. [1,2,3] → [1,2,3,1]
  '*×       '# For each, repeat the string "*" that many times
             #  i.e. [1,2,3,1] → ["*","**","***","*"]
     j       # Prepend spaces to make all items of a length equal to the (implicit) input
             #  i.e. ["*","**","***","*"] and 3 → ["  *"," **","***","  *"]
      €û     # Palindromize each string
             #  i.e. ["  *"," **","***","  *"] → ["  *  "," *** ","*****","  *  "]
        »    # Join the list by newlines (and output implicitly)
             #  i.e. ["  *  "," *** ","*****","  *  "] → "  *  \n *** \n*****\n  *  "
\$\endgroup\$
2
\$\begingroup\$

05AB1E (legacy), 16 10 bytes

L·<'**Ć.c»

Try it online!

Explanation:

L·<'**Ć.c»
L          : Create a range [1..input]
 ·<        : 2n-1 every element
   '**     : Multiply every element with "*"
      Ć    : Append the first element to the end
       .c  : Centralize elements
         » : Print out with newlines

Previous solution:

µ¾·>'**¼})Ć.c»

Try it online!

Explanation:

µ¾·>'**I¾-ú¼})Ć»
 ¾·>'**I¾-ú      : Create the row with padding and push to stack
           ¼     : Increment the counter
µ           }    : Loop until the counter reaches the input
             )   : Enclose stack to a list
              Ć  : Append the head to the end
               » : Print out the stack with newlines
\$\endgroup\$
  • 2
    \$\begingroup\$ No need to mark as noncompeting \$\endgroup\$ – ASCII-only Dec 23 '18 at 4:21
2
\$\begingroup\$

Bash: 126120

As there is no purpose, there is one:

for((z=$1-1;z;z--)){ printf -v s "%$((($1-z)*2-1))s" ""
printf "%$((2*$1-z))s\n" "${s// /*}";};printf "%$((1+$1))s\n" \*

This could be written:

#!/bin/bash
               #
              for\
            ((z=$1-
          1;z;z--));do
        printf -v s "%$((
     ($1-z)*2-1))s" "" #fil
   printf "%$((2*$1-z))s\n" \
 "${s// /*}";done;printf "%$((1
          +$1))s\n"\
              \*
              ##

In use:

set -- 12
for((z=$1-1;z;z--)){ printf -v s "%$((($1-z)*2-1))s" ""
printf "%$((2*$1-z))s\n" "${s// /*}";};printf "%$((1+$1))s\n" \*
            *
           ***
          *****
         *******
        *********
       ***********
      *************
     ***************
    *****************
   *******************
  *********************
            *

Or into the script:

./chrismas.sh 6
      *
     ***
    *****
   *******
  *********
      *
\$\endgroup\$
  • \$\begingroup\$ another bash solution squished down to 69 bytes :) \$\endgroup\$ – roblogic Aug 22 at 14:48
  • \$\begingroup\$ nice! Publish, I will give you my upvote! \$\endgroup\$ – F. Hauri Aug 22 at 22:16
  • \$\begingroup\$ (U could save 1 char by using \** instead of "**"! ;) \$\endgroup\$ – F. Hauri Aug 22 at 22:20
2
\$\begingroup\$

Intel 4004 machine code, 59 bytes

This 4-bit chip was the first commercial microprocessor, introduced in 1971. Multiplication and division were performed in software, and the accumulator could not be copied to one of the 16 registers except by swapping values.

40 33 50 0F A0 F8 B0 A0 1C 02 A1 B0 50 0F C0 24
20 A0 F8 50 2B 24 2A A1 90 F5 50 2B 24 20 A0 F8
50 2B 24 0C 53 E0 24 0D 53 E0 C0 14 32 53 E0 F8
40 2B C0 53 F0 B3 B0 A0 B1 50 02

The assembly code requires this python emulator for meaningful output.

jun start

mainloop:
    jms printline
    ld r0
    dac
    xch r0
    ld r0
    jcn an mainloop
    ld r1
    xch r0
    jms printline
    bbl 0

printline:
    fim r2 32
    ld r0
    dac
    jms printx

    fim r2 42
    ld r1
    sub r0
    ral
    jms printx

    fim r2 32
    ld r0
    dac
    jms printx

    ;carriage return
    fim r2 12
    jms $3e0
    fim r2 13
    jms $3e0

    bbl 0

printx: 
    jcn az ditch
    jms $3e0
    dac
    jun printx
ditch:
    bbl 0

start:
    jms $3f0 ; input
    xch r3
    xch r0 ; running total
    ld r0
    xch r1 ; permanent total
    jms mainloop

Sample run:

$ python intel4004-emu/main.py tree.4004 
8
       *       
      ***      
     *****     
    *******    
   *********   
  ***********  
 ************* 
***************
       *       
\$\endgroup\$
1
\$\begingroup\$

Language: Erlang, Char count: 183 (2 relevant spaces)

Here is an Erlang version, ~181chars:

-module (x).
-export ([t/1]).

t(N) ->
	t(N,0).
t(0,N) ->
	io:format("~s~s~n",[string:copies(" ",N),"*"]);
t(H,S) ->
	io:format("~s~s~n",[string:copies(" ",H),string:copies("*",(S*2)+1)]),
	t(H-1,S+1).

(btw, happy Christmas to everyone!)

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

Language: Scala, Char count: 128 (1 relevant space)

My Scala version. I'm glad I have found the * operator for strings (String implicitly promoted to RichString).

  def tree(n:Int) {
    def vals(n:Int,k:Int) = ((1 to n) map { i => (k - i, (i * 2) - 1) }).toList
    for(j <- vals(n,n) ::: vals(1,n)) 
      println(" " * j._1 + "*" * j._2)
  }
\$\endgroup\$
1
\$\begingroup\$

Language: Nemerle+Nextem, Char count: 129 (1 relevant space)

Nemerle with Nextem:

type s=string;
module t {
    public Main(a : array[s]) : void {
    	def t = int.Parse(a[0]);
    	def x(i) { print s(' ',t-i) + s('*',i*2+1) }
    	$[0..t].Iter(x);
    	x(0)
    }
}

Char count: 128

Edit: Made it take an arg Edit2: Imperative now

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

Here's how I would do it in Python, very straightforward, only 103 characters:

import sys
n=int(sys.argv[1])
for i in range(n): print ('*'*(2*i+1)).center(2*n)
print '*'.center(2*n)
\$\endgroup\$
1
\$\begingroup\$

Language: C, Char count: 433 (1 relevant space)

C version. Not short, not pretty, but it works.

#include <stdio.h>

void printLevel(int level, int width)
{
    int i;
    int count = level + (level - 1);
    int spaces = width - count;
    int lowerBound = spaces / 2;
    int upperBound = width - lowerBound;
    for (i = 0; i < width; i++) {
        if (i >= lowerBound && i < upperBound) {
            printf("*");
        } else {
            printf(" ");
        }
    }
    printf("\n");
}

void makeTree(int level)
{
    int i;
    int width = level * 2 - 1;
    for (i = 1; i <= level; i++) {
        printLevel(i, width);
    }
    printLevel(1, width);
}

int main(int argc, char **argv)
{
    int level = atoi(argv[1]);
    makeTree(level);
}
\$\endgroup\$
1
\$\begingroup\$

PHP (133 relevant characters):

function xmastree($h) {
    for($i=0;$i<$h;++$i)
        echo str_repeat(' ',$h-$i-1).str_repeat('*',2*$i+1)."\n";
    echo str_repeat(' ',$h-1)."*\n";
}
\$\endgroup\$
1
\$\begingroup\$

Common Lisp, 117 essential characters:

(defun x (n)
  (dotimes (v n)
    (format t "~v:@<~v{*~}~>~%"
            (1- (* 2 n))
            (1+ (* 2 v))
            '(())))
  (format t "~v:@<*~>~%" (1-(* 2 n)))

Are there any format gurus out there who know a better way to get repeating arbitrary characters?

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

Java version. 189 character

class P
{
	static String p(int n, String s) 
	{
		return --n < 1 ? s : p(n, s) + s;
	}

	public static void main(String[] a) 
	{
		for (int N = new Integer(a[0]), i = -1; i++ < N;) 
			System.out.println(p(N - i % N, " ") + p(i % N * 2 + 1, "*"));
	}
}
\$\endgroup\$
1
\$\begingroup\$

Language: Php, Char count: 110 (3 relevant spaces)

<? function x($n,$a,$t){return $n?str_repeat(' ',$n).$a.x($n-1,"*$a"," $t"):$t;}echo x($argv[1],"\n","*\n");

A bit of php recursion to reduce the count of chars to 110.

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

FreePascal:

program xmastree;

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes
  { you can add units after this };

var x,y,h:integer;

{$IFDEF WINDOWS}{$R xmastree.rc}{$ENDIF}

procedure printRow(sp,st:integer);
var i:integer;
begin
    for i := 1 to sp do begin
    write(' ');
  end;
    for x := 1 to st do begin
    write('*');
  end;
    for x := 1 to sp do begin
    write(' ');
  end;
    writeln();
end;

begin
    val(ParamStr(1),h);
  for y := 1 to h do begin
    printRow(h-y,(y-1)*2+1);
  end;
  printRow(h-1,1);
end.

Output for xmastree.exe 9

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

Language: C, Char count: 116

I realized I could improve on my original design:

main(int c,char**v){char l[99],i=0;for(c=atoi(1[v]);i<c;printf("%*s%.*s\n",c,l,i++,l))l[i]=42;printf("%*c\n",c,42);}

Different approach (119 characters):

s[99],w,i=0;p(n){printf("%*.*s\n",w+n,n*2+1,s);}main(int c,char**v){w=atoi(v[1]);for(memset(s,42,99);i<w;p(i++));p(0);}

Old version (123 characters):

main(int c,char**v){char*l=calloc(c=atoi(v[1]),2),i=0;for(;i<c;printf("%*s%.*s\n",c,l,i++,l))l[i]=42;printf("%*c\n",c,42);}

(One byte can be saved by putting char *l=... in the for loop. That makes it non-standard, however (though gcc still accepts it).)

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

Fortran 90

A bit modified, so the tree trunk looks more proportional to the height of the tree.

    write(*,*) 'how high a tree? '; read(*,*)n
    write(*,'(a,a)') (repeat(' ',n-i),repeat('*',2*i-1),i=1,n)
    write(*,'(a,a)') (repeat(' ',n-1),repeat('*',1),i=1,n/5+1)
    end
\$\endgroup\$
1
\$\begingroup\$

VBScript, 106 characters

n = WScript.Arguments(0)
For i = 1 To n
  WScript.Echo Space(n-i+1) & String(2*i-1, "*")
Next
WScript.Echo Space(n) & "*"

Usage and output example:

> cscript christmastree.vbs 7 //nologo
       *
      ***
     *****
    *******
   *********
  ***********
 *************
       *
\$\endgroup\$
1
\$\begingroup\$

Golfscript - 27 chars

~:i,0+{.i\-(' '*\.)+'*'*n}%

~:i  # eval the command line arg, store in i  
,0+  # create a list [0..i-1] add 0 to the end  
{}%  # map this block over the list  
.    # make a copy of the list element 
i\-  # subtract the list element from i 
(    # decrease by one more  
' '* # multiply the result by ' '
\    # swap, so the list element is back on top of stack
.)+  # duplicate, add one, add the two numbers together
'*'* # multiply the result by '*'
n    # put a newline here
\$\endgroup\$
  • \$\begingroup\$ nice, i did mine before seeing yours, was about to refactor it to look like this \$\endgroup\$ – Claudiu Jun 10 '10 at 6:29
1
\$\begingroup\$

Q, 54

{-1(-:)[((x+(!)x),x)]$(((&)((!)(2*x))mod 2),1)#\:"*";}

example:

q){-1(-:)[((x+(!)x),x)]$(((&)((!)(2*x))mod 2),1)#\:"*";} 10
         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************
         *
\$\endgroup\$
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\$

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.