Tower builder algorithm — JavaScript
While practising algorithms I came across some interesting ones. I decided to write about some of them and the way I approach and solve them.
The one that I will be talking about in this post is towerBuilder
. This is a function that takes as parameters an integer which represents the number of levels the tower should have.
The exciting part is that the returning value should be an array with strings which represents each level with spaces and “*” depending on the floor level.
Firstly I created some tests to validate my results.
The way that I usually approach is by creating a variable for the output
.
let output = [];
Then I created a function to make the math of the total spaces needed for any string/level.
const setCharts = (index) => index * 2 + 1
And the actual job is done by the for loop where:
- I define the variable
stars
and assign the return value of the earlier created function passing the index of the loop. - I define the variable
space
and assign the return value of the earlier created function passing the number of floors (subtracting one) divided by 2 (as we need equal spaces on both sides) - And I push in into
output
:
${number of spaces}${stars}${number of spaces}
Finally, right after the loop ends, I return the output and the final algorithm is looking like:
All the tests are passing and there may be other good ways of solving this but that is the way I think it makes the most sense.