Instructions
Write a function that accepts a positive number N. The function should console log a pyramid shape with N levels using the # character. Make sure the pyramid has spaces on both the left and right hand sides
// Examples
pyramid(1)
// '#'
pyramid(2)
// ' # '
// '###'
pyramid(3)
// ' # '
// ' ### '
// '#####'
Solution - For loops
The trick with this one is to find the midpoint. To get the midpoint use Math.floor((2 *n -1)/ 2).
Firstly create a variable called 'midpoint' that stores the midpoint of our pyramid. Iterate through rows starting from 0. Create an empty string called 'level', then iterate through some columns starting with 0. The amount to iterate through is 2 * n -1. Now to check if the column should add '#' to level or a space to level. To know this, check if the midpoint - current row is less than or equal to current column AND midpoint + current row is greater than or equal to current column. If both are true add '#' to level, else add a space to level. Once the iteration through columns is complete log out the current level string.
Create a variable named midpoint that stores the midpoint of our pyramid
From 0 to n, iterate through rows
Create an empty string 'level'
From 0 to columns, iterate through rows
IF the column should have
add '#' to level
ELSE
add a space, to level
console log level
const pyramid = (n) => {
const midpoint = Math.floor((2 * n - 1) / 2);
for (let row = 0; row < n; row++) {
let level = '';
for (let column = 0; column < 2 * n - 1; column++) {
if (midpoint - row <= column && midpoint + row >= column) {
level += '#';
} else {
level += ' ';
}
}
console.log(level);
}
}
Solution - Recursion
Check if row is equal to n, if so we have hit the end of our problem and should return. Check if level length is equal to 2 * n -1. If true log the level and return the function with n and row +1. Else get the midpoint of n and create a variable called add. If the midpoint - current row is less than or equal to level length AND midpoint + row ≥ level length, add = '#'. Else add = space ' '. Return the function with n, row and level + add
Check if row === n
if level length === 2 * n - 1
console log level
return pyramid(n, row+1)
midpoint = Math.floor((2 * n - 1) / 2)
add variable add
if midpoint - row is less then or equal to level.length AND midpoint + row ≥ level.length
add = #
else
add = ' ' empty space
return pyramid with add variable added to string
const pyramid = (n, row = 0, level = '') => {
// Check if row === n return is so
if (row === n) {
return
}
// Check level length
if (level.length === 2 * n - 1) {
console.log(level)
return pyramid(n, row + 1)
}
// Get mid point
const midpoint = Math.floor((2 * n - 1) / 2)
// variable string to add to level
let add
// Check if we should add a # or space
if (midpoint - row <= level.length && midpoint + row >= level.length) {
add = '#'
} else {
add = ' '
}
// next call to pyramid
pyramid(n, row, level + add)
}