04/07/2021

[Java] Draw fractal H tree

Fractals certainly build beautiful shapes, in this exercise we are tasked with creating an H tree, that is a tree where given a starting point which is the center of the horizontal line in the H, all corners of the H repeat the pattern until a given depth.

Example:

depth = 0, no tree

depth = 1, H

depth = 2;

H H

 H

H H

We can solve this recursively by calculating for a given center point, the boundaries of the horizontal line and drawing that, then for those boundaries, calculating the top and bottom point of the vertical lines at those centers and drawing those, finally going deeper and repeat the pattern.

The total number of H we draw is linked to the depth: 4^depth, which is also the running time of our algorithm as we must go through all those points to draw the H.

Using a stack, we only add at most depth points to it from a given start, therefore keeping the space to a minimum.

You can check my implementation of drawHTree on my Gist. No tests for this since I didn't actually implement the line drawing portion.

No comments:

Post a Comment

With great power comes great responsibility