12 December, 2013

A Christmas tree in 46 bytes

As holiday season is near, I came across one of the old source codes, which was written originally in C for a small competition. The goal was to display the following tree with a source code of minimal length:


The solution ported to MATLAB is 46 characters long:

for w=[0:8 0]fprintf('%*.*d0\n',8+w,w*2,0),end

A zero character – which follows the d character – is wired into the string, so the remaining number of the zeros in a line is 0, 2, 4... The \n stands for the line break.

The trick is to use the capabilities of string formatting:

  • The first parameter – belongs to the first asterisk – stands for the width of the displayed number. It should start from eight and increased by one in each step.
  • The second parameter – belongs to the second asterisk – is for giving the precision: since we are displaying an integer value, the print function treats this as leading zeros. This parameter shall be increased by two in each step.
  • The third parameter – belongs to the %d identifier – tells, that we want to print a zero value with the given parameters.

This way we can have leading spaces and leading zeros in the same function call. The last value of vector w is zero: it generates us the trunk of the Cristmas tree.


New comment

comments powered by Disqus