Hey folks,
I’m doing FCC top 10 js algorithm exercices YT video
I’d love to have feedback on 2 possible solutions for the pyramid shape function
Given an integer, the function logs to console a pyramid shape, example
// pyramid(2)
// ' # '
// '###'
Here’s my solution (basically I “measure” the distance from the center to determine which character must be added to str)
function pyramid(n) {
for (let i = 1; i<= n; i++) {
let str = ''
for (let j = 1; j <= 2*n-1; j++) {
if (Math.abs(j-n) < i) {
str += '#'
}else{
str += ' '
}
}
console.log(str)
}
}
Whereas the suggested solution does something slightly different, see below.
I’m trying to get good coding habits, and I was wondering if there was one reason to prefer one solution over the other, or if they are equivalent.
Thank you!!!
function pyramid(n) {
const mid = Math.floor((2*n-1)/2)
for(let row=0; row<n; row++){
let line = ''
for(let col=0; col<2*n-1; col++){
if( col >= mid - row && col<= mid + row ){
line += '#'
}else{
line += ' '
}
}
console.log(line)
}
}