Code Golf Christmas Edition: How to print out a Christmas tree of height N

93

15

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!

TheSoftwareJedi

Posted 2008-12-25T12:48:11.343

Reputation: 1 275

Answers

46

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

ephemient

Posted 2008-12-25T12:48:11.343

Reputation: 1 601

With just 9 more characters you can give this function a name: c=:[:((\:i.@#),}.)"1[:$&'*'"0[:>:0,~i. – ephemient – 2009-07-06T20:45:51.753

12What, do you guys use some sort of J documentation library to understandable-ize the code? :) – None – 2009-11-20T01:14:20.027

98

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

strager

Posted 2008-12-25T12:48:11.343

Reputation:

I found this version online that's only 127 bytes when you delete unnecessary characters.

– JosiahRyanW – 2019-11-14T00:15:27.467

2my brain feels f.....sick – None – 2009-01-22T00:14:07.687

5Oh my god. – anonymous coward – 2009-07-07T00:04:45.223

65

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. 

MkV

Posted 2008-12-25T12:48:11.343

Reputation: 751

Can be golfed to 44: say$"x($a-$_),"*"x($_*2+1)for 0..($a=<>)-1,0, assuming standard input is allowed instead of command line argument. Otherwise, replace <> with pop and it's 45 chars. – Tomas – 2014-02-01T02:04:57.850

Smaller perl implementation of same, only 81 chars

$,="\n";$a=pop;print map{$"x($a-$_).'*'x($_*2+1)}(0...$a-1);print$,.$"x$a."*\n";
 – Hasturkun  – 2008-12-25T16:07:14.953

Adding $n=$ARGV[0]; at the beginning (cost = 12 chars), then replacing all subsequent occurrences of $ARGV[0] with $n (savings = 6 chars each, times 3 occurrences) will get you a net 6 character reduction in total length. – None – 2008-12-25T16:08:01.423

now 79 chars

$,="\n";$a=pop;print map{$"x($a-$).'*'x($2+1)}0...$a-1;print$,.$"x$a."\n"; – Hasturkun – 2008-12-25T16:13:18.810

64: $,="\n";$a=pop;print map{$"x($a-$).'*'x($*2+1)}0...$a-1,0,-1; – Kent Fredric – 2008-12-25T16:26:51.950

62 $,=$/;$a=pop;print map{$"x($a-$).'*'x($*2+1)}0...$a-1,0,-1; – Hasturkun – 2008-12-25T16:29:36.047

56: $a=pop;print map{$"x($a-$).'*'x($*2+1).$/}0...$a-1,0; – Hasturkun – 2008-12-25T16:34:05.430

50, but you need to assume perl -E ( 5.10 ) : $a=pop;say $"x($a-$).'*'x($*2+1) for 0...$a-1,0; – Kent Fredric – 2008-12-25T16:42:16.817

55, $a=pop;print map{$"x($a-$).'*'x($*2+1).$/}0...$a-1,0; – Hasturkun – 2008-12-25T16:45:46.573

52: print $"x($a-$),'*'x($*2+1),$/for 0...($a=pop)-1,0 – Kent Fredric – 2008-12-25T16:55:45.620

50! print$"x($a-$),'*'x($*2+1),$/for 0..($a=pop)-1,0 – Hasturkun – 2008-12-25T16:59:07.873

25Holy crap... perl truly is unreadable. – None – 2008-12-25T17:20:53.603

@zenazn, it seems like that initially, but I would say the same thing about chinese. Once you learn it, it makes perfect sense. – Kent Fredric – 2008-12-25T17:22:15.377

8@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. – Kent Fredric – 2008-12-25T17:23:47.717

5@zenazn: proof, you can see us collaborating and improving each others code above, this proves WE can read EACH OTHERS code perfectly fine. – Kent Fredric – 2008-12-25T17:28:20.950

1PS: 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. – None – 2008-12-25T18:11:12.317

someone tipped me off on this one(outputs to stderr, though) 49: warn$"x($a-$),'*'x($*2+1),$/for 0..($a=pop)-1,0 – Hasturkun – 2008-12-25T20:17:57.787

If you are using Perl 5.10, you could replace print, with say. – Brad Gilbert b2gills – 2008-12-25T22:03:57.510

Your character count is 49. The space is not significant. – None – 2008-12-25T23:21:40.723

@Kent. Yes, the same way you can get used to count in binary. 10 + 10 - 11 = ( 100 - 11 ) = 1 ... :-/ – None – 2008-12-26T01:41:15.043

Perl...Is there nothing he can't do – None – 2008-12-30T04:35:46.263

1@zenazn: You haven't seen unreadable until you've seen APL. :-) – None – 2009-04-23T00:26:46.320

2

@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. http://stackoverflow.com/questions/392788/1088931#1088931

– ephemient – 2009-07-06T20:01:58.443

1

@RobH: You haven't seen unreadable until you've seen Whitespace ( http://en.wikipedia.org/wiki/Whitespace_(programming_language) )

– None – 2009-11-20T01:33:03.017

1I point out that the J solution is around half this length... – None – 2009-11-20T01:42:34.073

Why did this win when J has smaller char count? – None – 2009-11-20T01:50:12.700

@Claudiu: Look at the dates. This was accepted long before the J solution was written. – ephemient – 2009-12-01T18:17:23.267

28

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

tzot

Posted 2008-12-25T12:48:11.343

Reputation: 647

8what 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 – None – 2008-12-26T00:46:59.537

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. – None – 2008-12-26T19:19:40.617

4This 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. – None – 2008-12-26T20:56:28.377

27

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

Jonas Gulle

Posted 2008-12-25T12:48:11.343

Reputation: 501

24

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!*

Zach Scrivena

Posted 2008-12-25T12:48:11.343

Reputation:

Can't make it work. First time I try though. – Fabinout – 2013-11-15T10:27:26.537

masochist! I like it – None – 2009-01-08T14:17:55.637

Very nice... you get +1 – None – 2009-04-26T04:49:03.127

2Delayed variable expansion can be enabled using the setlocal enabledelayedexpansion command. – Helen – 2009-07-30T17:49:19.790

dude. seriously? – None – 2009-12-01T02:34:36.327

21

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

user4812

Posted 2008-12-25T12:48:11.343

Reputation:

dang I was hoping nobody tried it in ruby yet. nice job. – None – 2008-12-25T15:37:29.380

This is a very nice line of Ruby. – None – 2008-12-25T17:17:15.683

Did I seem too abrubt? Sorry, not my intention! Merry XMas! :) – None – 2008-12-25T20:08:25.357

Didn't mean to be mean either, and of course you were right! Merry Xmas! – None – 2008-12-25T20:47:47.053

I recently found the "Try Ruby" webpage, it looks like such a lovely programming language! :) – None – 2008-12-26T00:04:30.060

You can replace +[1] with <<1 and ARGV with $* (-3 characters) – None – 2008-12-26T08:20:13.740

Nice solution. I've translated it to code here http://stackoverflow.com/questions/392788/1089859#1089859

– None – 2009-07-07T00:42:55.400

1On 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. – None – 2010-09-14T10:05:31.130

14

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:

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

CMS

Posted 2008-12-25T12:48:11.343

Reputation:

13

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

Hynek -Pichi- Vychodil

Posted 2008-12-25T12:48:11.343

Reputation: 350

11Good lord, what the hell is that? – None – 2009-08-06T18:34:19.747

1Just read man page ;-) – None – 2009-08-08T05:54:23.290

12

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

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

ZeD

Posted 2008-12-25T12:48:11.343

Reputation:

Actually, it's 57 characters, only the ' ' space is significant as per the question specifications. – None – 2008-12-27T15:05:39.363

11

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

Gracenotes

Posted 2008-12-25T12:48:11.343

Reputation:

11

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

tzot

Posted 2008-12-25T12:48:11.343

Reputation: 647

Uhm seriously, wtf? I don't understand a single line of that :P – None – 2008-12-26T00:10:41.310

dc is a reverse-polish calculator. 'man dc' is the obvious way to go :) – None – 2008-12-26T03:56:30.027

6

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

joel.neely

Posted 2008-12-25T12:48:11.343

Reputation: 161

get rid of "public static void main", use a static block and compile with java 6 ;) – Fabinout – 2013-11-15T10:28:50.950

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) – Kevin Cruijssen – 2017-09-25T13:47:55.257

Your new character count is 251 (1 relevant space) – None – 2008-12-25T16:16:31.923

6

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

matyr

Posted 2008-12-25T12:48:11.343

Reputation:

6

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;}

jmucchiello

Posted 2008-12-25T12:48:11.343

Reputation:

using std; anyone? – None – 2008-12-25T23:09:27.033

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. – None – 2008-12-26T00:26:26.037

Your version is more inefficient than mine, because it has to create strings, my version just prints the characters it needs. :) – pyon – 2008-12-26T02:34:52.190

6

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)

ZeD

Posted 2008-12-25T12:48:11.343

Reputation:

5

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

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

Jaykul

Posted 2008-12-25T12:48:11.343

Reputation: 223

5

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.

user10639

Posted 2008-12-25T12:48:11.343

Reputation: 59

m,⍨⌽0 1↓m← -> (⌽,0 1↓⊢) – ngn – 2018-02-02T12:27:27.960

5

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, ΤΖΩΤΖΙΟΥ.

user49117

Posted 2008-12-25T12:48:11.343

Reputation:

5

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

Øyvind Skaar

Posted 2008-12-25T12:48:11.343

Reputation:

5

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

LoranceStinson

Posted 2008-12-25T12:48:11.343

Reputation:

4

Jelly, 12 bytes

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

Try it online!

Erik the Outgolfer

Posted 2008-12-25T12:48:11.343

Reputation: 38 134

4

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="")
    *
   ***
  *****
 *******
*********
    *

djhurio

Posted 2008-12-25T12:48:11.343

Reputation: 1 113

4

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.

Nils Pipenbrinck

Posted 2008-12-25T12:48:11.343

Reputation:

This has the same problem as my first cut in Java; it isn't a complete program with use of a command-line argument! – None – 2008-12-25T15:59:13.517

Oh? Is this required?

No problem. I'll fix that. – None – 2008-12-25T16:04:22.603

It's 138 characters when all unnecessary newlines are removed. – Can Berk Güder – 2008-12-25T16:21:20.087

I count 133 (just removed all whitespace and checked the filesize) – None – 2008-12-25T16:38:13.377

4

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

Can Berk Güder

Posted 2008-12-25T12:48:11.343

Reputation: 161

3

Charcoal, 9 bytes (noncompeting)

G↗↘←N*M↓*

Try it online!

Verbose

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

Try it online!

ASCII-only

Posted 2008-12-25T12:48:11.343

Reputation: 4 687

3

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  *  "

Kevin Cruijssen

Posted 2008-12-25T12:48:11.343

Reputation: 67 575

3

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

Ryan Burrow

Posted 2008-12-25T12:48:11.343

Reputation: 61

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

– HyperNeutrino – 2019-11-08T15:12:10.547

1

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

– Ryan Burrow – 2019-11-08T18:48:11.367

2Oh 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). – HyperNeutrino – 2019-11-08T19:12:35.863

You can save another byte with ++j<a-i – Jo King – 2019-11-13T01:33:19.387

3

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

Aaron Maenpaa

Posted 2008-12-25T12:48:11.343

Reputation:

Your character count is 98 (2 significant spaces, those in quotes) – None – 2008-12-25T23:37:36.713

3

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" "*"

Alastair

Posted 2008-12-25T12:48:11.343

Reputation:

golfed down to 70 bytes :) – roblogic – 2019-08-22T14:34:08.813

3

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

Yar

Posted 2008-12-25T12:48:11.343

Reputation:

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. – None – 2009-07-08T05:35:43.470

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. – None – 2009-07-08T09:22:45.803

2

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.

Maciej Goszczycki

Posted 2008-12-25T12:48:11.343

Reputation: 153

2

K 33

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

rrr

Posted 2008-12-25T12:48:11.343

Reputation: 31

2

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

F. Hauri

Posted 2008-12-25T12:48:11.343

Reputation: 2 654

another bash solution squished down to 69 bytes :) – roblogic – 2019-08-22T14:48:18.783

nice! Publish, I will give you my upvote! – F. Hauri – 2019-08-22T22:16:43.593

(U could save 1 char by using \** instead of "**"! ;) – F. Hauri – 2019-08-22T22:20:20.630

2

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

krinistof

Posted 2008-12-25T12:48:11.343

Reputation: 431

2No need to mark as noncompeting – ASCII-only – 2018-12-23T04:21:17.860

2

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

wyldstallyns

Posted 2008-12-25T12:48:11.343

Reputation: 401

2

K (oK), 33 bytes

{(x+1)#(-x+1+!x)$x#x("**",)\"* "}

Try it online!

scrawl

Posted 2008-12-25T12:48:11.343

Reputation: 1 079

2

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.

theage

Posted 2008-12-25T12:48:11.343

Reputation: 121

2

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.

FireFly

Posted 2008-12-25T12:48:11.343

Reputation: 7 107

2

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)

Can Berk Güder

Posted 2008-12-25T12:48:11.343

Reputation: 161

2

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

?>

Jeremy Ruten

Posted 2008-12-25T12:48:11.343

Reputation:

You can save several characters by building the string, then echoing it. I think. Try that out. – None – 2008-12-26T00:10:59.907

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. – None – 2008-12-26T00:19:52.243

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 – None – 2008-12-26T00:24:04.357

Saved a char by putting $r=.. inside the for. Also, I say newline characters should be one byte, not two. =] – None – 2008-12-26T00:46:20.037

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. – None – 2008-12-26T00:53:51.533

2

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?

Svante

Posted 2008-12-25T12:48:11.343

Reputation: 121

2

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

Helen

Posted 2008-12-25T12:48:11.343

Reputation: 131

2

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

BenAlabaster

Posted 2008-12-25T12:48:11.343

Reputation:

2

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

Arnauld

Posted 2008-12-25T12:48:11.343

Reputation: 111 334

1

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

user1329846

Posted 2008-12-25T12:48:11.343

Reputation: 11

1

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

Sasori

Posted 2008-12-25T12:48:11.343

Reputation: 11

1

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


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

Mark Miller

Posted 2008-12-25T12:48:11.343

Reputation: 151

1

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)

wolfhammer

Posted 2008-12-25T12:48:11.343

Reputation: 1 219

1

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

tomsmeding

Posted 2008-12-25T12:48:11.343

Reputation: 2 034

1

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.

Chromane

Posted 2008-12-25T12:48:11.343

Reputation: 161

1

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

prashanth

Posted 2008-12-25T12:48:11.343

Reputation: 111

Wait, does that display the trunk? – Johannes Kuhn – 2013-12-12T19:56:32.123

yes, :+1 would do that – prashanth – 2013-12-12T20:05:55.200

1

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

Shaggy

Posted 2008-12-25T12:48:11.343

Reputation: 24 623

1

Python 2, 56 bytes

i=n=input()
exec"i=~-i%n;print' '*i+'*'*(n*2-i+~i);"*-~n

Try it online!

xnor

Posted 2008-12-25T12:48:11.343

Reputation: 115 687

1

Japt, 11 bytes

õ_ç* êÃp* û

Try it online!

Oliver

Posted 2008-12-25T12:48:11.343

Reputation: 7 160

1

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

Jo King

Posted 2008-12-25T12:48:11.343

Reputation: 38 234

1

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.

cyclaminist

Posted 2008-12-25T12:48:11.343

Reputation: 191

Thanks! Good catch! – cyclaminist – 2018-12-23T11:49:51.470

1

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.

Titus

Posted 2008-12-25T12:48:11.343

Reputation: 13 814

Save 2 bytes using variable variables: Try it online!

– Night2 – 2019-10-13T13:50:40.267

1

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

roblogic

Posted 2008-12-25T12:48:11.343

Reputation: 554

1

Keg, 42 38 32 23 bytes

:&1ɧ1⑷:⑻$-⑬*$⑵;`*`*⑸(
'

Try it online!

-9 bytes due to generating odd numbers inside of the map

Answer History

32 Bytes

¿&1(⑻|:2+)1^⑷:;½ℤ⑻$-⑬*^`*`*⑸(,
,

Try it online!

-6 bytes due to using a mapping approach

38 Bytes

:&®l1(©l|⑬©l*,:`*`*,
,2+©l;®l)&⑬*,`*`,

-4 bytes due to operator (space string)

Funny story: I almost said this was 40 bytes before I realised that I forgot how to count.

Try it online!

I might as well place up the Keg Christmas tree for the year seeing as how it's almost December!

Explained

:&®l    #Store the amount of lines in variable l and the register
1   #Push the number of stars per row
(©l|    #Repeat variable l times
    ⑬©l*,   #Print that amount of spaces
    :`*`*,  #Print that amount of stars

    ,   #Print a literal newline
    2+  #Increment the number of stars
    ©l;®l   #Update the amount of spaces to print
)
&⑬*,`*`,    #Print the bottom row

Lyxal

Posted 2008-12-25T12:48:11.343

Reputation: 5 253

1

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

JosiahRyanW

Posted 2008-12-25T12:48:11.343

Reputation: 2 600

1

Charcoal, 12 bytes

G<N*‖↑¶M⊖θ←*

Try it online

explanation

G<N*             #Draw a triangle size input N with character "*"
      ‖↑           #Mirror the triangle so it is the right way round
        ¶          #Newline
         M⊖θ←    #move left input-1 
               *   #"*" character
                   #the result is implicitly printed

mabel

Posted 2008-12-25T12:48:11.343

Reputation: 1 489

Nice answer! I took the liberty of creating a TIO link so others can see it in action, if you'd liked to edit it into your post: https://tio.run/##ASkA1v9jaGFyY29hbP//77ynPO@8ririgJbihpHCtu@8reKKls644oaQKv//NQ

– Malivil – 2019-12-19T18:25:56.963

my bad @Malivil! I meant to add one, but forgot, thank you :) – mabel – 2019-12-19T18:33:02.343

1

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

cheng81

Posted 2008-12-25T12:48:11.343

Reputation:

1

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

Jonas Oberschweiber

Posted 2008-12-25T12:48:11.343

Reputation:

1

Language: Python, Char count: 104

Another take at python. Note that the question requested for a script, not a function.

import sys
n= int(sys.argv[1])
c= lambda s: s.center(2*n)
print "\n".join(c("*"*(2*i+1)) for i in range(n)); print c("*")

$ py ax 11
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
*********************
          *

tzot

Posted 2008-12-25T12:48:11.343

Reputation: 647

1

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

Cody Brocious

Posted 2008-12-25T12:48:11.343

Reputation:

1

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

Germán

Posted 2008-12-25T12:48:11.343

Reputation:

1

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)

Shane Tomlinson

Posted 2008-12-25T12:48:11.343

Reputation:

1

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

jmucchiello

Posted 2008-12-25T12:48:11.343

Reputation:

1

Language: Pike

101 Relevant characters

int main (int c, array a) {
    int n=(int)a[1], i,l;
    for(;i<=n; l = ++i < n ? i : 0)
        write(" " *(n-l) + "*" * (l*2+1) +"\n");
}

some

Posted 2008-12-25T12:48:11.343

Reputation: 111

1

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

strager

Posted 2008-12-25T12:48:11.343

Reputation:

1

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, "*"));
 }
}

Kire Haglin

Posted 2008-12-25T12:48:11.343

Reputation:

1

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.

Eineki

Posted 2008-12-25T12:48:11.343

Reputation:

1

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

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

feihtthief

Posted 2008-12-25T12:48:11.343

Reputation:

1

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

ldigas

Posted 2008-12-25T12:48:11.343

Reputation:

A slightly golfier version for 107 bytes :)

– roblogic – 2019-08-22T10:05:24.150

1

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

Helen

Posted 2008-12-25T12:48:11.343

Reputation: 131

1

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

gnibbler

Posted 2008-12-25T12:48:11.343

Reputation: 14 170

nice, i did mine before seeing yours, was about to refactor it to look like this – None – 2010-06-10T06:29:55.447

1

Q, 54

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

example:

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

tmartin

Posted 2008-12-25T12:48:11.343

Reputation: 3 917

1

Python-3x, 119 bytes

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

Praneeth

Posted 2008-12-25T12:48:11.343

Reputation: 111

1You skipped both the beginning “Given a number N” and the end “with its ‘trunk’ consisting of only a centered ‘*’” of requirement. – manatwork – 2015-06-17T15:25:10.600

I corrected to give user N value and * as trunk in the end – Praneeth – 2015-06-17T17:26:30.670

2

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.

– M. I. Wright – 2015-06-17T22:40:55.160

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. – manatwork – 2015-06-18T14:14:46.420

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. – Praneeth – 2015-06-18T15:11:13.283

0

SOGL V0.12, 11 10 bytes

ƨ*αak} *¹╚

Try it Here!

Explanation:

     }      implicitly started loop, repeated input times
ƨ*          push "**"
  α         append that to the variable A, here defaulted to an empty string
   a        load the variable A
    k       remove the first characters
       *    push "*"
        ¹   wrap in an array
         ╚  center horizontally

dzaima

Posted 2008-12-25T12:48:11.343

Reputation: 19 048

0

Excel VBA, 72 Bytes

Anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window

For i=1To[A1]:[B1]=i:?Spc([A1]-i)[Rept("*",2*B1-1)]:Next:?Spc([A1-1])"*"

Taylor Scott

Posted 2008-12-25T12:48:11.343

Reputation: 6 709

0

Python 3, 83 bytes

f=lambda n:'\n'.join([' '*(n-1-i)+'*'*(i*2+1)for i in range(n)])+'\n'+' '*(n-1)+'*'

Dat

Posted 2008-12-25T12:48:11.343

Reputation: 879

0

JavaScript, 90 89 bytes

f=(l,n=1,s="")=>l+1?s+=f(l-1,n+2,l?`*`.repeat(n).padStart(l+n)+`
`:"*".padStart(n/2+1)):s

Try it online!


Alternative:

f=(l,n=1)=>l+1&&f(l-1,n+2,console.log(l?"*".repeat(n).padStart(l+n):"*".padStart(n/2+1)))

Try it online!

Oliver

Posted 2008-12-25T12:48:11.343

Reputation: 7 160

0

APL(NARS), 37 chars, 74 bytes

{⊃⍵{(' '⍴⍨⍺-⍵),'*'⍴⍨1+⍵×2}¨0,⍨0,⍳⍵-1}

test:

  h←{⊃⍵{(' '⍴⍨⍺-⍵),'*'⍴⍨1+⍵×2}¨0,⍨0,⍳⍵-1}
  h 5
     *    
    ***   
   *****  
  ******* 
 *********
     *    
  h 1
 *
 *
  h 2
  * 
 ***
  * 
  h 3
   *  
  *** 
 *****
   *  

Ot: It seems that your sys for know if i'am a human not work good in this chellphone (so I write this because possible this step is not taken)

RosLuP

Posted 2008-12-25T12:48:11.343

Reputation: 3 036

0

Python 2, 119 116

This one generates the tree on one line:

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

It's too bad you have to import the sys module in Python before being able to read argv.

Being used from Command Prompt:

C:\Users\User4\Desktop>treeprint.py 6
     *
    ***
   *****
  *******
 *********
***********
     *

I have a Linux box but it can't connect to the Internet and only has Python 2.4, in case you're wondering why I'm using Windows.

cjfaure

Posted 2008-12-25T12:48:11.343

Reputation: 4 213

0

Dart, 174 characters

main(p){var x=-1,r='',a=int.parse(p[0]),b=a,f=(x,y,[z='']){var s='';while(x-->0)s+=y;return s+z;};while(a-->0){x+=2;r+=f(a,' ')+f(x,'*','\n');}print('$r${f(b-1,' ','*')}');}

mezoni

Posted 2008-12-25T12:48:11.343

Reputation: 101

0

R, 94 chars

Christmas is over, but anyway:

t=function(N){
  f=function(i)cat(rep(" ",N-i),rep("*",2*i-3),"\n",sep="")
  lapply(2:N,FUN=f);f(2)
}

For trees of height 2 or more:

> t(2)  > t(3)  > t(5)
*        *         *
*       ***       ***
         *       *****
                *******
                   *

popojan

Posted 2008-12-25T12:48:11.343

Reputation: 31

We have posted similar R solutions in three minutes ;) – djhurio – 2014-01-08T14:37:47.253

becomes obsolete, see @djhurio solution – popojan – 2014-01-08T14:38:33.130

btw, I have got attracted to this site by the "2014" problem. I have got a 20 chars solution in R, but cannot post it as the question is protected from newbies ;) – popojan – 2014-01-08T14:51:20.687

Would be nice to see your 20 char solution for the "2014" ;) – djhurio – 2014-01-08T15:24:49.910

1sum(T+T:exp(T+pi))-T – popojan – 2014-01-08T15:30:03.087

Nice one. Should I add it to my answer mentioning you as an author? – djhurio – 2014-01-09T07:02:41.857

done, see: http://codegolf.stackexchange.com/a/17877/13849

– djhurio – 2014-01-09T09:25:13.990

0

Python3,81 bytes

n=int(input());
for j in range(n):
 print(' '*(n-j)+'*'*(2*j+1))
print(' '*n+'*')

try it online

Saksham Jain

Posted 2008-12-25T12:48:11.343

Reputation: 11

0

Wren, 91 bytes

Fn.new{|n|
for(i in 0...n)System.print(" "*(n-i)+"*"*(2*i+1))
System.print(" "*n+"*")
}

Try it online!

user85052

Posted 2008-12-25T12:48:11.343

Reputation:

0

x86 machine code, 42 40 bytes

Same limitation as in previous x86 answer (N < 10) applies. It may be lifted by replacing the first four lines with the following six (+6 bytes):

start:
    mov si, 82h
    lodsw
    xchg al, ah
    and ax, 0F0Fh
    aad

Assembly source code:

start:
    mov si, 82h
    lodsb
    aaa
    xchg ax, cx
    mov dx, 0A2Ah
    mov di, dx
    push cx
_loop:
    push cx
    rep stosb
    xchg ax, dx
    mov cx, bx
    rep stosb
    stosw
    inc bx
    inc bx
    pop cx
    xchg ax, dx
    loop _loop
    pop cx
    rep stosb
    xchg ax, dx
    stosw
    xchg ax, dx
    mov ax, 0924h
    stosb
    int 21h
    ret

Dmitry Shechtman

Posted 2008-12-25T12:48:11.343

Reputation: 121

0

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

Max Ullinger

Posted 2008-12-25T12:48:11.343

Reputation:

1Note: 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) – None – 2008-12-25T20:06:26.420

0

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) + "*")

ePharaoh

Posted 2008-12-25T12:48:11.343

Reputation:

0

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

Hynek -Pichi- Vychodil

Posted 2008-12-25T12:48:11.343

Reputation: 350

0

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

Jason S

Posted 2008-12-25T12:48:11.343

Reputation: 187

0

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)+'*'

Leon Tayson

Posted 2008-12-25T12:48:11.343

Reputation:

0

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)

Matt Lewis

Posted 2008-12-25T12:48:11.343

Reputation:

0

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();
        }
    }
}

Metro Smurf

Posted 2008-12-25T12:48:11.343

Reputation:

0

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

friol

Posted 2008-12-25T12:48:11.343

Reputation:

I got it in 29 characters: http://stackoverflow.com/questions/392788/1088931#1088931

– ephemient – 2009-07-06T20:00:02.393

0

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

Tolgahan Albayrak

Posted 2008-12-25T12:48:11.343

Reputation:

0

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

Matajon

Posted 2008-12-25T12:48:11.343

Reputation:

0

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 "*"

Alex Mcp

Posted 2008-12-25T12:48:11.343

Reputation:

0

Lua, 113 significant chars

s=string.rep;n=tonumber(arg[1]);r=print;for i=0,n do l=s(" ", n-i)..s("*",(n-(n-i))*2+1);r(l)end r(s(" ",n).."*")

RCIX

Posted 2008-12-25T12:48:11.343

Reputation:

The two ns in s("*",(n-(n-i))*2+1) can be canceled out, yielding s("*",i*2+1). – cyclaminist – 2018-12-23T00:47:03.847

0

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;}

Graphics Noob

Posted 2008-12-25T12:48:11.343

Reputation:

0

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

Claudiu

Posted 2008-12-25T12:48:11.343

Reputation: 3 870

0

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)

"  *   
 ***  
***** 
  *   "

pimvdb

Posted 2008-12-25T12:48:11.343

Reputation: 821