Tower builder algorithm — JavaScript

Zaharia Anton
2 min readFeb 13, 2021

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response