5. Builder Tower

99 阅读1分钟

Build a pyramid-shaped tower, as an array/list of strings, given a positive integer number of fllors, A tower block is represented with '*' character.

For Example,a tower with 3 floors looks like this:

[  "  *  ",  " *** ",  "*****"]

And a tower with 6 floors looks like this:

[  "     *     ",  "    ***    ",  "   *****   ",  "  *******  ",  " ********* ",  "***********"]
我的解法:

😱----------无----------  没-解-出-来🌚
unlock solutions
解法1function towerBuilder(n) {
    return Array.from({length: n}, (v, k) => {
        var spaces = ' '.repeat(n-k-1)
        return spaces + '*'.repeat(k+k+1) + spaces
    })
}

🉑剖析学习点:
String.prototype.repeat() ===> str.repeat(count)
Array.from({length:3})    ===> [undefiend, undefined, undefined]
(v, k) ===> (value, key)  ===> undefined,0undefined,1undefined,2



解法2function towerBuilder(nFloors) {
    var tower = []
    for (var i = 0; i < nFloorsl i++) {
        tower.push(' '.repeat(nFloors-i-1)
            + '*'.repeat((i*2)-1)
            + ' '.repeat(nFloors-i-1)
        )
    }
    return tower
}