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.

102 Answers 102

46
\$\begingroup\$

J, 24 characters

(,{.)(}:@|."1,.])[\'*'$~

   (,{.)(}:@|."1,.])[\'*'$~5
    *    
   ***   
  *****  
 ******* 
*********
    *    

Explanation:

'*'$~5
*****

[\'*'$~5
*    
**   
***  
**** 
*****

Then }:@|."1 reverses each row and strips off the last column, and ,. staples it to ].

Then ,{. pastes the first column onto the bottom.

Previous entries:

29 characters, no spaces at all.

   ((\:i.@#),}.)"1$&'*'"0>:0,~i.3
  *
 ***
*****
  *
   ((\:i.@#),}.)"1$&'*'"0>:0,~i.11
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
*********************
          *

   NB. count from 1 to n, then 1 again
   >:0,~i.3
1 2 3 1
   NB. replicate '*' x times each
   $&'*'"0>:0,~i.3
*
**
***
*
   NB. reverse each row
   (\:i.@#)"1$&'*'"0>:0,~i.3
  *
 **
***
  *
   NB. strip off leading column
   }."1$&'*'"0>:0,~i.3

*
**

   NB. paste together
   ((\:i.@#),}.)"1$&'*'"0>:0,~i.3
  *
 ***
*****
  *
\$\endgroup\$
  • \$\begingroup\$ With just 9 more characters you can give this function a name: c=:[:((\:i.@#),}.)"1[:$&'*'"0[:>:0,~i. \$\endgroup\$ – ephemient Jul 6 '09 at 20:45
  • 11
    \$\begingroup\$ What, do you guys use some sort of J documentation library to understandable-ize the code? :) \$\endgroup\$ – RCIX Nov 20 '09 at 1:14
96
\$\begingroup\$

Brainfuck, 240 characters

              ,
             >++
            +++++
           +[-<---
          --->],[>+
         +++++++[-<-
        ----->]<<[->+
       +++++++++<]>>]<
      [->+>+>>>>>>>+<<<
     <<<<<<]>>>>++++++++
    [-<++++>]>++++++[-<++
   +++++>]+>>>++[-<+++++>]
  <<<<<<[-[>.<-]<[-<+>>+<]<
 [->+<]>>>>>[-<.>>+<]>[-<+>]
>.<<++<<<-<->]>>>>>>>-[-<<<<<
           <.>>>
           >>>]<
           <<<<.

Not yet done. It works, but only with single-digit numbers.

EDIT: Done! Works for interpreters using 0 as EOF. See NOTEs in commented source for those with -1.

EDIT again: I should note that because Brainfuck lacks a standard method for reading command line arguments, I used stdin (standard input) instead. ASCII, of course.

EDIT a third time: Oh dear, it seems I stripped . (output) characters when condensing the code. Fixed...

Here's the basic memory management of the main loop. I'm sure it can be heavily optimized to reduce the character count by 30 or so.

  1. Temporary
  2. Copy of counter
  3. Counter (counts to 0)
  4. Space character (decimal 32)
  5. Asterisk character (decimal 42)
  6. Number of asterisks on current line (1 + 2*counter)
  7. Temporary
  8. New line character
  9. Temporary?
  10. Total number of lines (i.e. input value; stored until the very end, when printing the trunk)

Condensed version:

,>++++++++[-<------>],[>++++++++[-<------>]<<[->++++++++++<]>>]<[->+>+>>>>>>>+<<<<<<<<<]>>>>++++++++[-<++++>]>++++++[-<+++++++>]+>>>++[-<+++++>]<<<<<<[-[>.<-]<[-<+>>+<]<[->+<]>>>>>[-<.>>+<]>[-<+>]>.<<++<<<-<->]>>>>>>>-[-<<<<<<.>>>>>>]<<<<<.

And the pretty version:

ASCII to number
,>
++++++++[-<------>]  = 48 ('0')

Second digit (may be NULL)
,
NOTE:   Add plus sign here if your interpreter uses negative one for EOF
[ NOTE: Then add minus sign here
 >++++++++[-<------>]
 <<[->++++++++++<]>>  Add first digit by tens
]

Duplicate number
<[->+>+>>>>>>>+<<<<<<<<<]>>

Space char
>>++++++++[-<++++>]

Asterisk char
>++++++[-<+++++++>]

Star count
+

New line char
>>>++[-<+++++>]<<<

<<<

Main loop
[
Print leading spaces
-[>.<-]

Undo delete
<[-<+>>+<]
<[->+<]
>>

Print stars
>>>[-<.>>+<]

Add stars and print new line
>[-<+>]
>.<
<++

<<<

-<->
End main loop
]

Print the trunk
>>>>>>>
-[-<<<<<<.>>>>>>]
<<<<<.

Merry Christmas =)
\$\endgroup\$
  • 1
    \$\begingroup\$ my brain feels f.....sick \$\endgroup\$ – JoshBerke Jan 22 '09 at 0:14
  • 4
    \$\begingroup\$ Oh my god. \$\endgroup\$ – anonymous coward Jul 7 '09 at 0:04
  • \$\begingroup\$ I found this version online that's only 127 bytes when you delete unnecessary characters. \$\endgroup\$ – JosiahRyanW 6 hours ago
63
\$\begingroup\$

Perl, 50 chars

(1 relevant spaces)

perl: one line version:

print$"x($a-$_),'*'x($_*2+1),$/for 0..($a=pop)-1,0

and now with more whitesapce:

print $"  x ( $a - $_ ),             #"# Syntax Highlight Hacking Comment
      '*' x ( $_ * 2  + 1),
      $/
for 0 .. ( $a = pop ) - 1, 0;

$ perl tree.pl 3
   *
  ***
 *****
   *
$ perl tree.pl 11
           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
           *
$ 

Expanded Explanation for Non-Perl Users.

# print $Default_List_Seperator ( a space )  
#     repeated ( $a - $currentloopiterationvalue ) times,
print $" x ( $a - $_ ), 
#"# print '*' repeated( $currentloopiteration * 2 + 1 ) times. 
  '*' x ( $_ * 2  + 1),
# print $Default_input_record_seperator ( a newline )
  $/
# repeat the above code, in a loop, 
#   iterating values 0 to ( n - 1) , and then doing 0 again
for 0 .. ( $a = pop ) - 1, 0;
# prior to loop iteration, set n to the first item popped off the default list, 
#   which in this context is the parameters passed on the command line. 
\$\endgroup\$
  • 25
    \$\begingroup\$ Holy crap... perl truly is unreadable. \$\endgroup\$ – zenazn Dec 25 '08 at 17:20
  • 8
    \$\begingroup\$ @zenazn, also, it should be noticed that most golfing is BAD code in any language. If this were a competition for the cleanest code, we could win that too. \$\endgroup\$ – Kent Fredric Dec 25 '08 at 17:23
  • 5
    \$\begingroup\$ @zenazn: proof, you can see us collaborating and improving each others code above, this proves WE can read EACH OTHERS code perfectly fine. \$\endgroup\$ – Kent Fredric Dec 25 '08 at 17:28
  • 1
    \$\begingroup\$ PS: Thanks for the explanation for non-Perl programmers. It's still pretty unreadable, but at least it makes sense. I guess you get used to it after a while. \$\endgroup\$ – zenazn Dec 25 '08 at 18:11
  • 2
    \$\begingroup\$ @RobH: J is the child of APL. In some senses, it's more unreadable because it doesn't use APL's character set with a special symbol for every operation -- it overloads ASCII characters with multiple meanings, instead. stackoverflow.com/questions/392788/1088931#1088931 \$\endgroup\$ – ephemient Jul 6 '09 at 20:01
27
\$\begingroup\$

Language: Python (through shell), Char count: 64 (2 significant spaces)

python -c "
n=w=$1
s=1
while w:
    print' '*w+'*'*s
    s+=2
    w-=1
print' '*n+'*'"

$ sh ax6 11
           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
           *
\$\endgroup\$
  • 8
    \$\begingroup\$ what I like most about this solution is that python makes it really hard to write obscure code, it's one of the most readable solutions \$\endgroup\$ – Georg Schölly Dec 26 '08 at 0:46
  • \$\begingroup\$ You're using the shell to process the argument, which isn't in the spirit of code golf IMO. Using "import sys" and "n=w=int(sys.argv[1])" and an indent of 1 character for the loop body, I come up with 89 characters for this version. \$\endgroup\$ – Joshua Swink Dec 26 '08 at 19:19
  • 4
    \$\begingroup\$ This is how I did it before. The spirit of this question is to have fun, and in addition there was no specification of using only one language :) See the brainfuck answer, for example; no arguments. \$\endgroup\$ – tzot Dec 26 '08 at 20:56
26
\$\begingroup\$

x86 asm 16-bit, 50 bytes

No assembly version yet? :)

    bits 16
    org 100h

    mov si, 82h
    lodsb
    aaa
    mov cx, ax
    mov dx, 1
    push cx 
    mov al, 20h
    int 29h
    loop $-2
    push dx
    mov al, 2ah
    int 29h
    dec dx
    jnz $-3
    pop dx
    mov al, 0ah
    int 29h
    inc dx
    inc dx
    pop cx
    loop $-23
    shr dx, 1
    xchg cx, dx
    mov al, 20h
    int 29h
    loop $-2
    mov al, 2ah
    int 29h
    ret

(Note: N is limited to 1 - 9 in this version)

G:\>tree 9
         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
         *

Download here

\$\endgroup\$
24
\$\begingroup\$

Language: Windows Batch Script (shocking!)

@echo off
echo Enable delayed environment variable expansion with CMD.EXE /V

rem Branches
for /l %%k in (1,1,%1) do (
set /a A=%1 - %%k
set /a B=2 * %%k - 1
set AA=
for /l %%i in (1,1,!A!) do set "AA=!AA! "
set BB=
for /l %%i in (1,1,!B!) do set BB=*!BB!
echo !AA!!BB!
)

rem Trunk
set /a A=%1 - 1
set AA=
for /l %%i in (1,1,!A!) do set "AA=!AA! "
echo !AA!*
\$\endgroup\$
  • \$\begingroup\$ masochist! I like it \$\endgroup\$ – Colin Pickard Jan 8 '09 at 14:17
  • \$\begingroup\$ Very nice... you get +1 \$\endgroup\$ – ojblass Apr 26 '09 at 4:49
  • 2
    \$\begingroup\$ Delayed variable expansion can be enabled using the setlocal enabledelayedexpansion command. \$\endgroup\$ – Helen Jul 30 '09 at 17:49
  • \$\begingroup\$ dude. seriously? \$\endgroup\$ – Earlz Dec 1 '09 at 2:34
  • \$\begingroup\$ Can't make it work. First time I try though. \$\endgroup\$ – Fabinout Nov 15 '13 at 10:27
21
\$\begingroup\$

Ruby, 64 bytes

n=ARGV[0].to_i
((1..n).to_a+[1]).each{|i|puts' '*(n-i)+'*'*(2*i-1)}

n=$*[0].to_i
((1..n).to_a<<1).each{|i|puts' '*(n-i)+'*'*(2*i-1)}

Merry Christmas all!

Edit: Improvements added as suggested by Joshua Swink

\$\endgroup\$
  • \$\begingroup\$ dang I was hoping nobody tried it in ruby yet. nice job. \$\endgroup\$ – esabine Dec 25 '08 at 15:37
  • \$\begingroup\$ This is a very nice line of Ruby. \$\endgroup\$ – zenazn Dec 25 '08 at 17:17
  • \$\begingroup\$ Did I seem too abrubt? Sorry, not my intention! Merry XMas! :) \$\endgroup\$ – tzot Dec 25 '08 at 20:08
  • \$\begingroup\$ Didn't mean to be mean either, and of course you were right! Merry Xmas! \$\endgroup\$ – user4812 Dec 25 '08 at 20:47
  • 1
    \$\begingroup\$ On 1.9, you can save some more chars: n=$*[0].to_i;puts [*1..n,1].map{|i|" "*(n-i)+"*"*(2*i-1)} brings it down to 58. \$\endgroup\$ – manveru Sep 14 '10 at 10:05
14
\$\begingroup\$

Language: C#, Char count: 120

static void Main(string[] a)
{
    int h = int.Parse(a[0]);

    for (int n = 1; n < h + 2; n++)
        Console.WriteLine(n <= h ?
            new String('*', n * 2 - 1).PadLeft(h + n) :
            "*".PadLeft(h + 1));
    }
}

Just the code, without formatting (120 characters):

int h=int.Parse(a[0]);for(int n=1;n<h+2;n++)Console.WriteLine(n<=h?new String('*',n*2-1).PadLeft(h+n):"*".PadLeft(h+1));

Version with 109 characters (just the code):

for(int i=1,n=int.Parse(a[0]);i<n+2;i++)Console.WriteLine(new String('*',(i*2-1)%(n*2)).PadLeft((n+(i-1)%n)));

Result for height = 10:

          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
          *
\$\endgroup\$
13
\$\begingroup\$

Language: dc (through shell) Char count: 83

A little bit shorter dc version:

dc -e '?d1rdsv[d32r[[rdPr1-d0<a]dsaxszsz]dsbx1-rd42rlbx2+r10Plv1-dsv0<c]dscxszsz32rlbx[*]p' <<<$1

EDIT: changed constant 10 into $1

\$\endgroup\$
  • 11
    \$\begingroup\$ Good lord, what the hell is that? \$\endgroup\$ – amischiefr Aug 6 '09 at 18:34
  • 1
    \$\begingroup\$ Just read man page ;-) \$\endgroup\$ – Hynek -Pichi- Vychodil Aug 8 '09 at 5:54
12
\$\begingroup\$

python, "-c" trick... @61 chars (and one line)

python -c"for i in range($1)+[0]:print' '*($1-i)+'*'*(2*i+1)"
\$\endgroup\$
  • \$\begingroup\$ Actually, it's 57 characters, only the ' ' space is significant as per the question specifications. \$\endgroup\$ – tzot Dec 27 '08 at 15:05
11
\$\begingroup\$

Here's a reasonably space-efficient Haskell version, at 107 characters:

main=interact$(\g->unlines$map(\a->replicate(g-a)' '++replicate(a*2-1)'*')$[1..g]++[1]).(read::[Char]->Int)

running it:

$ echo 6 | runhaskell tree.hs
     *
    ***
   *****
  *******
 *********
***********
     *

Merry Christmas, all :)

\$\endgroup\$
10
\$\begingroup\$

Language: dc (through shell), Char count: 119 (1 significant space)

Just for the obscurity of it :)

dc -e "$1dsnsm"'
[[ ]n]ss
[[*]n]st
[[
]n]sl
[s2s1[l2xl11-ds10<T]dsTx]sR
[lndlslRxlcdltlRxllx2+sc1-dsn0<M]sM
1sclMxlmlslRxltxllx
'

$ sh ax3 10
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
          *
\$\endgroup\$
  • \$\begingroup\$ Uhm seriously, wtf? I don't understand a single line of that :P \$\endgroup\$ – Aistina Dec 26 '08 at 0:10
  • \$\begingroup\$ dc is a reverse-polish calculator. 'man dc' is the obvious way to go :) \$\endgroup\$ – tzot Dec 26 '08 at 3:56
6
\$\begingroup\$

Better C++, around 210 chars:

#include <iostream>
using namespace std;
ostream& ChristmasTree(ostream& os, int height) {
    for (int i = 1; i <= height; ++i) {
        os << string(height-i, ' ') << string(2*i-1, '*') << endl;
    }
    os << string(height-1, ' ') << '*' << endl;
    return os;
}

Minimized to 179:

#include <iostream>
using namespace std;ostream& xmas(ostream&o,int h){for(int i=1;i<=h;++i){o<<string(h-i,' ')<<string(2*i-1,'*')<<endl;}o<<string(h-1,' ')<<'*'<<endl;return o;}
\$\endgroup\$
  • \$\begingroup\$ using std; anyone? \$\endgroup\$ – strager Dec 25 '08 at 23:09
  • \$\begingroup\$ strager - when I started there were only a couple std::'s and 'using namespace std;' was a lot of text. I suppose now that would be fewer characters. \$\endgroup\$ – jmucchiello Dec 26 '08 at 0:26
  • \$\begingroup\$ Your version is more inefficient than mine, because it has to create strings, my version just prints the characters it needs. :) \$\endgroup\$ – pyon Dec 26 '08 at 2:34
6
\$\begingroup\$

Language: python, no tricks, 78 chars

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

Groovy 62B

n=args[0]as Long;[*n..1,n].any{println' '*it+'*'*(n-~n-it*2)}

_

n = args[0] as Long
[*n..1, n].any{ println ' '*it + '*'*(n - ~n - it*2) }
\$\endgroup\$
5
\$\begingroup\$

Improving ΤΖΩΤΖΙΟΥ's answer. I can't comment, so here is a new post. 72 characters.

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

Using the "python -c" trick, 61 characters.

python -c "
for i in range($1)+[0]:
   print ('*'*(2*i+1)).center(2*$1)
"

I learned the center function and that "python -c" can accept more than one line code. Thanks, ΤΖΩΤΖΙΟΥ.

\$\endgroup\$
5
\$\begingroup\$

C# using Linq:

    using System;
    using System.Linq;
    class Program
        {
            static void Main(string[] args)
            {
                int n = int.Parse(args[0]);
                int i=0;
                Console.Write("{0}\n{1}", string.Join("\n", 
                   new int[n].Select(r => new string('*',i * 2 + 1)
                   .PadLeft(n+i++)).ToArray()),"*".PadLeft(n));
            }
       }

170 charcters.

int n=int.Parse(a[0]);int i=0;Console.Write("{0}\n{1}",string.Join("\n",Enumerable.Repeat(0,n).Select(r=>new string('*',i*2+1).PadLeft(n+i++)).ToArray()),"*".PadLeft(n));
\$\endgroup\$
5
\$\begingroup\$

AWK, 86 characters on one line.

awk '{s="#";for(i=0;i<$1;i++){printf"%"$1-i"s%s\n","",s;s=s"##"}printf"%"$1"s#\n",""}'

echo "8" | awk '{s="#";for(i=0;i<$1;i++){printf"%"$1-i"s%s\n","",s;s=s"##"}printf"%"$1"s#\n",""}'
        #
       ###
      #####
     #######
    #########
   ###########
  #############
 ###############
        #

cat tree.txt
3
5

awk '{s="#";for(i=0;i<$1;i++){printf"%"$1-i"s%s\n","",s;s=s"##"}printf"%"$1"s#\n",""}' tree.txt
   #
  ###
 #####
   #
     #
    ###
   #####
  #######
 #########
     #
\$\endgroup\$
5
\$\begingroup\$

Language: Java, Char count: 219

class T{ /* 219 characters */
  public static void main(String[] v){
    int n=new Integer(v[0]);
    String o="";
    for(int r=1;r<=n;++r){
      for(int s=n-r;s-->0;)o+=' ';
      for(int s=1;s<2*r;++s)o+='*';
      o+="%n";}
    while(n-->1)o+=' ';
    System.out.printf(o+"*%n");}}

For reference, I was able to shave the previous Java solution, using recursion, down to 231 chars, from the previous minimum of 269. Though a little longer, I do like this solution because T is truly object-oriented. You could create a little forest of randomly-sized T instances. Here is the latest evolution on that tack:

class T{ /* 231 characters */
  public static void main(String[] v){new T(new Integer(v[0]));}}
  String o="";
  T(int n){
    for(int r=1;r<=n;++r){
      x(' ',n-r);x('*',2*r-1);o+="%n";}
    x(' ',n-1);
    System.out.printf(o+"*%n");
  }
  void x(char c,int x){if(x>0){o+=c;x(c,x-1);}
 }
\$\endgroup\$
  • \$\begingroup\$ Your new character count is 251 (1 relevant space) \$\endgroup\$ – tzot Dec 25 '08 at 16:16
  • \$\begingroup\$ get rid of "public static void main", use a static block and compile with java 6 ;) \$\endgroup\$ – Fabinout Nov 15 '13 at 10:28
  • \$\begingroup\$ I know it's been almost 9 years (lol..) but you can golf some things: class T{public static void main(String[]v){long n=new Long(v[0]),r=1,s;String o="";for(;r<=n;r++){for(s=n-r;s-->0;)o+=' ';for(;++s<2*r;)o+='*';o+="\n";}while(n-->1)o+=' ';System.out.println(o+"*");}} (199 characters/bytes) \$\endgroup\$ – Kevin Cruijssen Sep 25 '17 at 13:47
5
\$\begingroup\$

Language:PowerShell, Char count: 41 (including 1 space)

1..$args[0]+1|%{" "*(30-$_)+"*"*($_*2-1)}
\$\endgroup\$
5
\$\begingroup\$

21 characters with dyalog APL.

m,⍨⌽0 1↓m←↑'*'\¨⍨1,⍨⍳

⍳ gives a vector of integers starting with 1.

1,⍨ adds a one to the end of the vector. This will be the foot of the tree.

'*'\¨⍨ gives a vector of *-strings with lengths given by the previous vector.

↑ transforms the vector to a matrix and adds spaces to the right.

m← stores the matrix in m.

0 1↓ drops zero rows and the first column.

⌽ reverses the matrix.

m,⍨ concatenates with m at the right side.

\$\endgroup\$
  • \$\begingroup\$ m,⍨⌽0 1↓m← -> (⌽,0 1↓⊢) \$\endgroup\$ – ngn Feb 2 '18 at 12:27
4
\$\begingroup\$

Language: C, Char count: 133

Improvement of the C-version.

char s[61];

l(a,b){printf("% *.*s\n",a,b,s);}

main(int i,char**a){
  int n=atoi(a[1]);memset(s,42,61);
  for(i=0;i<n;i++)l(i+n,i*2+1);l(n,1);
}

Works and even takes the tree height as an argument. Needs a compiler that tolerates K&R-style code.

I feel so dirty now.. This is code is ugly.

\$\endgroup\$
  • \$\begingroup\$ This has the same problem as my first cut in Java; it isn't a complete program with use of a command-line argument! \$\endgroup\$ – joel.neely Dec 25 '08 at 15:59
  • \$\begingroup\$ Oh? Is this required? No problem. I'll fix that. \$\endgroup\$ – Nils Pipenbrinck Dec 25 '08 at 16:04
  • \$\begingroup\$ It's 138 characters when all unnecessary newlines are removed. \$\endgroup\$ – Can Berk Güder Dec 25 '08 at 16:21
  • \$\begingroup\$ I count 133 (just removed all whitespace and checked the filesize) \$\endgroup\$ – Nils Pipenbrinck Dec 25 '08 at 16:38
4
\$\begingroup\$

R (62 bytes)

I did not see R solution yet. Correct me if I missed it.

for(i in c(1:N,1))cat(rep(" ",N-i),rep("*",2*i-1),"\n",sep="")

Output:

> N <- 3
> for(i in c(1:N,1))cat(rep(" ",N-i),rep("*",2*i-1),"\n",sep="")
  *
 ***
*****
  *
> 
> N <- 4
> for(i in c(1:N,1))cat(rep(" ",N-i),rep("*",2*i-1),"\n",sep="")
   *
  ***
 *****
*******
   *
> 
> N <- 5
> for(i in c(1:N,1))cat(rep(" ",N-i),rep("*",2*i-1),"\n",sep="")
    *
   ***
  *****
 *******
*********
    *
\$\endgroup\$
3
\$\begingroup\$

Language: C, Char count: 176 (2 relevant spaces)

#include <stdio.h>
#define P(x,y,z) for(x=0;x++<y-1;)printf(z);
main(int c,char **v){int i,j,n=atoi(v[1]);for(i=0;i<n;i++){P(j,n-i," ")P(j,2*i+2,"*")printf("\n");}P(i,n," ")printf("*\n");}
\$\endgroup\$
3
\$\begingroup\$

Shell version, 134 characters:

#!/bin/sh
declare -i n=$1
s="*"
for (( i=0; i<$n; i++ )); do
    printf "%$(($n+$i))s\n" "$s"
    s+="**"
done
printf "%$(($n))s\n" "*"
\$\endgroup\$
3
\$\begingroup\$

Language: Python, Significant char count: 90

It's ugly but it works:

import sys
n=int(sys.argv[1])
print"\n".join(" "*(n-r-1)+"*"*(r*2+1)for r in range(n)+[0])

...

$ python tree.py 13
            *
           ***
          *****
         *******
        *********
       ***********
      *************
     ***************
    *****************
   *******************
  *********************
 ***********************
*************************
            *
\$\endgroup\$
  • \$\begingroup\$ Your character count is 98 (2 significant spaces, those in quotes) \$\endgroup\$ – tzot Dec 25 '08 at 23:37
3
\$\begingroup\$

Since this is a CW: I don't like that code golfs are always organized in terms of "number of characters" or somesuch. Couldn't they be organized in terms of number of instructions for the compiler/interpreter (or some similar criterion)? Here is the Ruby solution again, and it's basically the same, but now for human consumption too:

SPACE = " "
ASTERISK = "*"
height_of_tree=ARGV[0].to_i
tree_lines = (1..height_of_tree).to_a
tree_lines.push 1 # trunk
tree_lines.each do | line |
   spaces_before = SPACE*(height_of_tree-line)
   asterisks = ASTERISK*(2*line-1) 
   puts spaces_before + asterisks
end
\$\endgroup\$
  • \$\begingroup\$ I agree with the first statement. In such terms, languages like perl have a starting advantage. Should be something like number of statemetns or the like. \$\endgroup\$ – ldigas Jul 8 '09 at 5:35
  • \$\begingroup\$ thanks... I asked a question about golf yesterday and the way to do it might be with "tokens"... that way name-length and so forth is not penalized. \$\endgroup\$ – Yar Jul 8 '09 at 9:22
3
\$\begingroup\$

Charcoal, 9 bytes (noncompeting)

G↗↘←N*M↓*

Try it online!

Verbose

Polygon(:UpRight, :DownRight, :Left, InputNumber(), "*")
Move(:Down)
Print("*")

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Jelly, 12 bytes

R”*ẋz⁶ṚŒBṁ‘Y

Try it online!

\$\endgroup\$
3
\$\begingroup\$

c: 151 116 115

Just giving it a whirl

i,j,a;main(c,v)int**v;{for(a=atoi(v[1]);i<a;i+=puts(""))for(j=0;j<a+i;)putchar(++j<a-i?32:42);printf("%*s",a,"*");}

Readable code:

i, j, a; 
main(c, v) int **v; {
    for (a = atoi(v[1]); i < a; i += puts(""))
        for(j = 0; j < a + i;)
            putchar(++j < a - i ? 32 : 42);
    printf("%*s", a, "*");
}

Try it online!

Code History:

main(int c, char **v){
    int i, j, a = atoi(v[1]);
    for (i = 1; i <= a; i++) {
        for (j = 0; j < a + i - 1; j++)
            putchar((j >= a - i) ? '*' : ' ');
        putchar('\n');
    }
    printf("%*s*\n", a - 1, "");
}
New contributor
Ryan Burrow is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Golf! This is good for a first submission; however, I see some easy improvements you can make by simply removing unnecessary spaces and newlines. Also, can you provide a link to test this? It's missing #include<stdio.h> and I'm getting segfaults: link \$\endgroup\$ – HyperNeutrino Nov 8 at 15:12
  • 1
    \$\begingroup\$ I think you're getting segfaults because you provided the number as an input rather than an argument link You also don't have to include the #include the compiler will yell at you but it will work. I left in the spaces because the challenge said to count characters ignoring whitespace and it makes it more readable \$\endgroup\$ – Ryan Burrow Nov 8 at 18:48
  • 2
    \$\begingroup\$ Oh okay. That makes sense, sorry not a C user :P Thanks for the explanation. And yeah, my bad, I forgot about that part of this challenge (haven't visited it in a while). \$\endgroup\$ – HyperNeutrino Nov 8 at 19:12
  • \$\begingroup\$ You can save another byte with ++j<a-i \$\endgroup\$ – Jo King yesterday

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.