This series of articles follows Stephen Grider's Udemy course in three different languages.
Today's question is a slight variation on the last one.
--- Directions
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)
' # '
' ### '
'#####'
1: Iterative Solution
JavaScript:
function pyramid(n) {
const columnCount = 2 * n - 1;
const midColumn = Math.floor(columnCount / 2);
for (let row = 0; row < n; row++) {
let level = '';
for (let column = 0; column < columnCount; column++) {
if (Math.abs(column - midColumn) <= row) {
level += '#';
} else {
level += ' ';
}
}
console.log(level);
}
}
Python:
def pyramid(n):
column_count = 2 * n - 1
mid_column = column_count // 2
for row in range(n):
level = ''
for column in range(column_count):
if abs(column - mid_column) <= row:
level += '#'
else:
level += ' '
print(level)
Java:
static void pyramid1(int n) {
int columnCount = 2 * n - 1;
int midColumn = columnCount / 2;
for (int row = 0; row < n; row++) {
StringBuilder level = new StringBuilder();
for (int column = 0; column < columnCount; column++) {
if (Math.abs(column - midColumn) <= row) {
level.append("#");
} else {
level.append(" ");
}
}
System.out.println(level);
}
}
2: Recursive Solution
Here I take an approach a bit different from the one introduced in the course.
JavaScript:
function pyramid(n, row = 0, level = '#') {
if (n === row) {
return;
}
if (level.length === 2 * n - 1) {
console.log(level);
return pyramid(n, row + 1);
}
level = level.length < 2 * row ? `#${level}#` : ` ${level} `;
pyramid(n, row, level);
}
Python:
def pyramid(n, row=0, level='#'):
if n == row:
return
if len(level) == 2 * n - 1:
print(level)
return pyramid(n, row+1)
level = f'#{level}#' if len(level) < 2 * row else f' {level} '
pyramid(n, row, level)
Java:
static void pyramid(int n) {
pyramid(n, 0, new StringBuilder("#"));
}
static void pyramid(int n, int row, StringBuilder level) {
if (n == row) {
return;
}
if (level.length() == 2 * n - 1) {
System.out.println(level);
pyramid(n, row + 1, new StringBuilder("#"));
return;
}
if (level.length() < 2 * row) {
level.insert(0, "#").append("#");
} else {
level.insert(0, " ").append(" ");
}
pyramid(n, row, level);
}
Thank you for reading. I do plan to write this series more often, so I hope to see you soon!
Top comments (0)