Sullivan Tobias
Sullivan Tobias

Reputation: 152

Pyramid Algorithm JS

I was messing around with some basic algorithms. I wanted to know if someone has a shorter version of this one in JS to display the pyramid:

const total= 30;
let line = 1;

for (let i = 1; i < total; i = i + 2) {
    console.log(' '.repeat(total / 2 - line) + '*'.repeat(i))
    line++;
}

Upvotes: 0

Views: 181

Answers (4)

trincot
trincot

Reputation: 350137

console.log(Array.from({length:15},(_,i)=>"*".repeat(i*2+1).padStart(15+i)).join`\n`);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

An even shorter approach by using a while statement.

This answer is highly inspired by the answer of Mister Jojo.

let s = '*',
    p = 15;
    
while (p--) {
    console.log(' '.repeat(p) + s)
    s += '**';
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

Girish Sasidharan
Girish Sasidharan

Reputation: 588

Same using map function

function pyramid(height) {
  return Array(height).fill('*')
    .map((current, index) =>
      ' '.repeat(height - index) +
      current.repeat(index).split('').join(' ') +
      ' '.repeat(height - index))
    .join('\n');
}
console.log(pyramid(30));

Upvotes: 0

Mister Jojo
Mister Jojo

Reputation: 22265

that ?

let s = '*'
for(let p=15;p--;) 
  {
  console.log( ' '.repeat(p) + s)
  s += '**'
  }
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions