DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #52 - Building a Pyramid

Challenge
Write a function that will draw a pyramid. The function should take one integer parameter that will describe how many lines tall the pyramid should be.

This challenge is simple, but requires a bit of reflection to get it right. Here is an example in Node.js hosted on Repl.it.

Example
pyramid(5);

Good luck!


This challenge comes from @aminnairi here on DEV! Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Latest comments (20)

Collapse
 
matrossuch profile image
Mat-R-Such

Python

def pyramid(line):
    if line == 1:   print('*')
    elif line == 0: print('')
    else:
        for i in range(line):
            print(' '*(line-i-1),'*'*(2*i+1))
Collapse
 
kvharish profile image
K.V.Harish

My solution in js

const padSpaceToSides = (str, len) => {
  const padlen = len - str.length,
    right = Math.ceil(padlen / 2),
    left = padlen - right;
  return str = Array(left + 1).join(' ') + str + Array(right + 1).join(' ');
},
pyramid = (height, atom = '*') => {
  const start = 1,
    step = 2;
  for(let i = start; i < height * 2; i += step) {
    console.log(padSpaceToSides(atom.repeat(i), height * 2 - 1));
  }
};

pyramid(10)

Output

Collapse
 
devparkk profile image
Dev Prakash
Collapse
 
delixx profile image
DeLiXx
function pyramid(i) {
    for( k = 1; i != 0; k++) {
        console.log(" ".repeat(--i) + "*".repeat(k*2-1));
    }
}
Collapse
 
gnsp profile image
Ganesh Prasad
const pyramid = n => Array(n).fill(1)
    .map((_, lineno) => lineno * 2 + 1)
    .map(x => [x, (n * 2 - 1 - x) / 2])
    .map(([x, y]) => [Array(x).fill('*').join(''), Array(y).fill(' ').join('')])
    .map(([x, y]) => `${y}${x}${y}`).join('\n');
Collapse
 
kerrishotts profile image
Kerri Shotts

My try. I used padStart and padEnd, and abused default parameters a bit, just for fun.

const PYRAMID = "*";
const AIR = "·";

const pyramid = (n, {maxWidth = (n * 2) - 1, leftPadding = maxWidth / 2} = {}) => 
    Array.from({length: n}, (_, idx, __, {width = (( idx + 1 ) * 2) - 1} = {}) => 
        PYRAMID.repeat(width)
            .padStart(idx + leftPadding + 1, AIR)
            .padEnd(maxWidth, AIR)
    ).join("\n");
Collapse
 
brightone profile image
Oleksii Filonenko

Rust:

pub fn pyramid(floors: usize) -> String {
    (0..floors)
        .map(|f| " ".repeat(floors - f - 1) + &"*".repeat(2 * f + 1))
        .collect::<Vec<_>>()
        .join("\n")
}
Collapse
 
jalawes profile image
Jamal

Javascript, can be run from the command line:

const floors = Number(process.argv[2]);

for (let currentFloor = 1; currentFloor <= floors; currentFloor += 1) {
  console.log(
    '*'.repeat(2 * currentFloor - 1)
      .padStart((floors + currentFloor - 1), ' '),
  );
}
Collapse
 
olekria profile image
Olek Ria

F#:

let pyramid (x: int) =
  let print maxWidth count =
    (String.replicate (maxWidth - count) " ") + (String.replicate (2*count-1) "*")

  let pr = (x - 1) * 2 + 1 |> print

  for i in [1..x] do
     i |> pr |> printfn "%s"
Collapse
 
eromanowski profile image
Eric • Edited
var pyramid = (height) => {
  var pyramidLayer = '*';
  width = height * 2;
  for(var i=1;i<width;i++) {
     if(i % 2 === 1) {
        console.log(pyramidLayer.padStart((width+i)/2, ' '));
    }
    pyramidLayer += '*';
  }
}
pyramid(5);