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.
Just discovered this community existed, I’ve got to make a post in my usual golfing lang:
Zsh, 70 bytes
l=() repeat $1 l=(${(l.++i.)}\* $^l' *') print -l $l ${(l.$1-1.)}'| |'
The key constructs here are
(l.ARITHMETIC EXPRESSION.)
, which left-pads, and$^l
, which expands the array like a cross product.a=(a b c); echo x$a
printsxa b c
, butecho x$^a
printsxa xb xc
.Interestingly,
print -l
was shorter than<<<
by one byte.I don’t know about how y’all feel about submissions in dedicated golfing languages/esolangs like this, but
Vyxal - 14 characters/SBCS bytes (22 UTF-8 bytes)
ɾ×*vṄ
| |JøĊ⁋
Vyxal is a stack-based esolang designed to do well in code-golf competitions just like this one. It’s far from the only golfing language in existence, there’s many more like 05AB1E, Jelly and Thunno 2. This one is just one I made in 2020 (yes creative naming I know, I just couldn’t think of anything better).
You can try the program online here
Explained:
ɾ×*vṄ`| |`JøĊ⁋ ɾ # Generate a list of numbers from 1 to the input. ×* # Repeat the character "*" n many times, for each n in the above list vṄ # Insert a space between each asterisk. Normally, Ṅ will join an entire list on spaces, but the v makes Ṅ apply to each item in a list. `| |`J # Append the string "| |" to that list - this is the stump of the tree øĊ # Centre each of the strings in the list, relative to the longest string in the list. This is a single built-in function (the ø indicates that it's a two-character function) ⁋ # Join the resulting list on newlines
For
input = 5
, the stack looks like so:ɾ×*vṄ`| |`JøĊ⁋ ɾ [1, 2, 3, 4, 5] ×* ["*", "**", "***", "****", "*****"] (* does the multiplication, the × is the character that pushes "*" to the stack - it was a later addition) vṄ ["*", "* *", "* * *", "* * * *", "* * * * *"] `| |`J ["*", "* *", "* * *", "* * * *", "* * * * *", "| |"] øĊ [" * ", " * * ", " * * * ", " * * * * ", "* * * * *", " | | "] ⁋ Output as in the original challenge post
As you can see, some built-ins automatically apply to each item in a list, as if you wrote
[
. ]Once again, I don’t mean to come in and ruin golf for everyone, I just want to see how such a language might be seen by the community.
Perl - 55 characters with say:
say ' 'x($N-$_).'* 'x$_ for 1..$N;say ' 'x($N-2).'| |';
JavaScript, 93 characters:
l=console.log,r='repeat',b=n=>{for(i=0;i++<n;l(' '[r](n-i)+'* '[r](i)));l(' '[r](n-2)+'| |')}