Code Kata: Christmas Tree

Inspired by a blog post of Dave Thomas I started to implement my technology learning roadmap by writing little code katas.

To kill two birds with one stone I first solve a programming puzzle with my lingua franca Python. That helped me to concentrate on solving the algorithmic part of the puzzle because I don’t have to constantly worry about syntax and semantics.

Then I did the whole thing again this time in the language I want to learn: Rust

To give You an example how that works I will elaborate on the Christmas tree kata. Ok, what is the Christmas tree? It’s a neat little programming exercise where You have to print a Christmas tree on the console.

e.g. a tree with height 2 looks like this:

 X
XXX
 |

and a tree with height 3 looks like this:

  X
 XXX
XXXXX
  |

How do You solve this? First of all You have to understand how many whitespaces and “X”s You will find in each line depending on the level.
So for a tree with height 2 there is one whitespace and one X in the first and no whitespace and 3 “X” in the second row and two whitespaces and one “|” in the third line.

Let’s make a little table to see where this is going:

row  WS   X   |
0    1    1   0
1    0    3   0
2    1    0   1

Same thing again for height 3

row  WS   X   |
0    2    1   0
1    1    3   0
2    0    5   0
3    2    0   1

I hope it becomes quite easy to see how the characters have to be printed out:
for whitespaces it is “height – current_row – 1”,
for “X” it is “2 * current_row + 1”
and the last line is always “height – 1” whitespaces plus the “|” character.

In Python it looks like this:

height = 3
for line in range(height):
    print (" " * (height-line-1)) + "X" * (2*line+1)
print (" " * (height-1)) + "|"

And now for something completely different: Rust
Rust is a strongly and statically typed language, so there is a bit more effort in writing this Kata down. It looks like this:


fn draw_christmas_tree(height: i32){
    let mut val: String = String::new();
    for i in 0..height {
        for j in 0..height-i{
            val.push_str(" ");
        }
         for k in 0..(2*i+1){
            val.push_str("X");
        }
        val.push_str("\n");
    }
    for j in 0..height{
        val.push_str(" ");
    }
    val.push_str("|");
    println!("{}", val);

}
fn main() {
    draw_christmas_tree(3);
}

Because in Rust You don’t have the smooth “repeat a string n times” syntax You have to iterate more often. I also tried to append the characters to a string buffer before printing them out so it looks a bit more different then the solution in python.