Challenge: Function that prints a n
big tree
Challenge: Function that prints a n
big tree
Write a function that prints an n
big tree, e.g. for n=5:
*
* *
* * *
* * * *
* * * * *
| |
Here is what I came up with in C:
N,i;a(n){for(i=N=N?N:n+2;i--;printf(i?"* "+(N-n-1<i):--n?"\n":"\n%*s",N,"| |"));n&&a(n);}
// the invocation isn't part of the golf:
main(){a(5);}
PS: Code blocks currently wrap around when they are too long, I've already submitted a patch to make them scroll horizontally instead.
You're viewing a single thread.
Python - 94 chars
I tried using some alternatives, but they all ended up more verbose than:
def a(n): for i in range(0,n): print(' '*(n-i)+'* '*(i+1)+' '*(n-i-1)) print(' '*(n-1)+'| |')
The list tools in python are great, but they all use keywords, so doing anything that doesn't directly do for and print is likely too much. You could make a list of strings for instance, and print it all out at once to save a 'print' but you'd end up using a for in list comprehension or a join or something, so you can't really save any characters afaict.
I'm sure someone will find a way to beat it tho!
4 0 ReplyJust for fun I asked ChatGPT and got a Python in 65 chars:
def p(n):print('\n'.join(' '*(n-i)+'* '*i for i in range(1,n+1)))
Since I'm most familiar with JavaScript I'll try that myself now
3 0 ReplyPoor ChatGPT, it's always so close but so far. This doesn't meet spec :)
It doesn't print the bottom row of ' | | ', and it misses the leading spaces.
Fixing it produces:
def p(n):print('\n'.join(' '*(n-i)+'* '*(i+1)+' '*(n-i-1) for i in range(0,n)));print(' '*(n-1)+'| |')
Which is 102 characters, so longer than before. Like I said, I tried the list comp route. You get rid of some stuff, but you add more unfortunately.
However, both me and ChatGPT made the mistake of printing spaces after, which tbh isn't necessary. That can give a bit of a boost:
def p(n):print('\n'.join(' '*(n-i)+'* '*(i+1) for i in range(0,n)));print(' '*(n-1)+'| |')
Which is 90, but applying it to my og answer:
def a(n): for i in range(0,n): print(' '*(n-i)+'* '*(i+1)) print(' '*(n-1)+'| |')
Yields 82.
Putting the loop on one line saves a couple characters though:
def a(n): for i in range(0,n):print(' '*(n-i)+'* '*(i+1)) print(' '*(n-1)+'| |')
Gets it to 80
4 0 ReplyOh I totally missed that the trunk was part of the spec, gotta fix my own answer too
4 0 Reply