Skip to content

Instantly share code, notes, and snippets.

@eldyvoon
Last active January 5, 2018 02:55
Show Gist options
  • Save eldyvoon/c2413a88b154d863d31fb4528034cc6f to your computer and use it in GitHub Desktop.
Save eldyvoon/c2413a88b154d863d31fb4528034cc6f to your computer and use it in GitHub Desktop.
Step and Pyramic tree in Javascript
steps(4);
//
#
##
###
####
pyramid(5)
//
#
###
#####
#######
#########
//solution for steps
function steps(n) {
for (let i = 0; i < n; i++) {
let stair = '';
for (let j = 0; j < n; j++) {
if (j <= i) {
stair += '#';
} else {
stair += '';
}
}
console.log(stair);
}
}
//solution for pyramid
function pyramid(n) {
const midpoint = Math.floor((2 * n - 1) / 2)
for (let row = 0; row < n; row++) {
let level = '';
for (let col = 0; col < 2 * n - 1; col++) {
if (midpoint - row <= col && midpoint + row >= col) {
level += '#';
} else {
level += ' ';
}
}
console.log(level);
}
}
//recursive solution for pyramid
function pyramid(n, row = 0, level = '') {
if (row === n) {
return;
}
if (level.length === 2 * n - 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 = ' ';
}
pyramid(n, row, level + add);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment