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.

  • l4sgc@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    1 year ago

    Just 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

    • KindaABigDyl@programming.dev
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      1 year ago

      Poor 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