Home > Software engineering >  Can't make pyramid of numbers
Can't make pyramid of numbers

Time:05-01

I Need to get this output:

1

2  3

4  5  6

7  8  9  10

11 12 13 14 15

What I've tried so far:

function getPyramid() {
  let nums = 0;
  for (let i = 1; i <= 15; i  ) {
    for (let n = 1; n < i; n  ) {
      console.log(n);

    }
    console.log('<br/>');

  }
  return nums;
}
getPyramid();

CodePudding user response:

    for (let i = 1 ; i <= 5; i  )
    {
      let s = []
      for (let x = i * (i - 1) / 2   1; x <= i * (i   1) / 2; x  )
      { 
        s.push(x)
      }
      console.log(s.join(" "))
    }

CodePudding user response:

Apart from notes given by jnpdx in the comments, I'd add some:

  • for better convention between programmers we tend to name varible nested in for-loop: i, j
  • <br/> for HTML new line, In JS we do \n for that!
  • number is same number = 1
  • Conditional_Operator (expression)?true:false instead of if/else
    function getPyramid(Lines) {
    let number = 1; // the counter to display on each line of pyramid!
    for (let i = 1; i <= Lines; i  ) {
        let str = '';//line to display
        for (let j = 1; j <= i; j  ) {
           str  = number  ;//incrementing counter
           str  = j!=i ? ' ' : ''; //to make space, but not at the end of line.
        }
       console.log(str);//display that line
    }
    }
    getPyramid(5);

CodePudding user response:

It is possible to do with one single loop

function getPyramid() {
  
let nums = 0;
let count = 1; 
let numbers = ''
  for (let i = 1; i <= 15; i  ) {
    if(count === nums){
         count  
         nums = 0;
         console.log(numbers)
         numbers = ''
     }
     nums   
     numbers  = i 
  }

}
getPyramid();

CodePudding user response:

A completely unnecessary attempt to do this in a functional style:

const ranged_array = (from, to) =>
  Array.from({ length: to - from   1 }, (_, i) => i   from);

const pyramid = (lines) =>
  ranged_array(1, lines)
    .reduce((a, v, i) => {
      const prev = a[i - 1];
      const last_num = prev && prev[prev.length - 1] || 0;
      a.push(ranged_array(last_num   1, last_num   v));
      return a;
    }, [])
    .map((v) => v.join(' '))
    .join("\n");

console.log(pyramid(5));

  • Related