0

I have been looking for a while for this answer and most results bring up people NOT wanting to push more than once, and its hard to find a straight forward solution / alternative.

I have been tasked with a exercise to output a tower in an array. It increments based on its floor size. For example.

[
  '  *  ', 
  ' *** ', 
  '*****'
]

I am still leaning the ropes of Javascript and I am intrigued to learn, here is what I have come up with:

function towerBuilder(floors) {
  let arr = [];
  let space = " ";
  let tower = "*"  

  for (i = 0; i < floors; i++) {
    arr.push(space, tower * i, space);
  }
    console.log(arr)
}

towerBuilder(3);

console.log shows (Array [ 0, NaN, 0, 0, NaN, 0, 0, NaN, 0 ]) - I guess multiplying a string is a bad idea.

I could probably create multiple for loops and have each push in its own loop, but that would look really messy.

Is there a way to push spaces and *'s multiplied by the for loop?

Thanks

4
  • 5
    you can't multiply strings, but you can use .repeat() Commented Jan 24, 2020 at 11:42
  • const totalNumberofRows = 5; let output=""; for (let i = 1; i <= totalNumberofRows; i++) { for (let j = 1; j <= i; j++) { output+=j + " "; } console.log(output); output=""; } Commented Jan 24, 2020 at 11:46
  • You need to get the length of the spaces to surround and the character to stuff in there so function towerBuilder(floors) { let arr = []; let space = " "; let tower = "*"; let b = floors + 1; while (--b) { let sx = space.repeat(floors - (b)); let tx = tower.repeat(b); let x = sx + tx + sx; arr.push(x); } return arr; } let t = towerBuilder(3); alert(t); Commented Jan 24, 2020 at 13:12
  • This is not truly a duplicate of the marked question given the desired output, voting to re-open. Commented Jan 24, 2020 at 13:16

1 Answer 1

0

 function towerBuilder(floors) {
      let arr = [];
      let tower = '*';
      let space = ' ';
      let total = (2 * floors) + 1;
      for (i = 0; i < floors; i++) {
        let count = (2 * i) + 1;
        let free = (total - count) / 2;
                     arr.push(`${space.repeat(free-1)}${tower.repeat(count)}${space.repeat(free-1)}`);
      }
      console.log(arr)
    }

    towerBuilder(3);

Sign up to request clarification or add additional context in comments.

4 Comments

this does not put spaces in the strings as the example desired output shows
Question was modified after answer was submitted. Answer corrected. Please undo downvote.
I was able to fix this without any issues so I still consider this the answer.
After the answer edit it produces the defined output. I would suggest i = 0; instead be let i = 0; to avoid a global however. I still consider the question to not be a duplicate of the marked one in the close note but only "related"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.