Skip to content

Instantly share code, notes, and snippets.

@uzorjchibuzor
Created July 29, 2018 21:35
Show Gist options
  • Save uzorjchibuzor/286b0a88d186f8d5a95a250bf318f09d to your computer and use it in GitHub Desktop.
Save uzorjchibuzor/286b0a88d186f8d5a95a250bf318f09d to your computer and use it in GitHub Desktop.
// iterative solution
function pyramid(n) {
const midPoint = Math.floor((2 * n - 1) / 2);
for (let row = 0; row < n; row++) {
let level = "";
for (let column = 0; column < n * 2 - 1; column++) {
if (midPoint - row <= column && midPoint + row >= column) {
level += "#";
} else {
level += " ";
}
}
console.log(level);
}
}
pyramid(4) // #
###
#####
#######
// recursive solution
function pyramid(n, row = 0, level = "") {
if (row === n) {
return;
}
if (level.length === n * 2 - 1) {
console.log(level);
return pyramid(n, row + 1);
}
const midPoint = Math.floor((2 * n - 1) / 2);
let add;
if (midPoint - row <= level.length && midPoint + row >= level.length) {
add = "#";
} else {
add = " ";
}
return pyramid(n, row, level + add);
}
pyramid(4) // #
###
#####
#######
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment