Wednesday, February 21, 2024
HomeSoftware EngineeringThe best way to Create a Pyramid Array in Javascript

The best way to Create a Pyramid Array in Javascript


The problem

Write a operate that when given a quantity >= 0, returns an Array of ascending size subarrays.

pyramid(0) => [ ]
pyramid(1) => [ [1] ]
pyramid(2) => [ [1], [1, 1] ]
pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]

Word: the subarrays ought to be crammed with 1s

The answer in Javascript

Possibility 1:

operate pyramid(n) {
  const res = [];
  for(let i = 0; i < n; i++){
    res.push([...Array(i+1)].fill(1))
  }
  return res;
}

Possibility 2:

operate pyramid(n) {
  return Array(n).fill().map((e,i)=>Array(i+1).fill(1))
}

Possibility 3:

const pyramid = n => Array(n).fill(1).map((x, i) => Array(i + 1).fill(1))

Take a look at instances to validate our answer

describe('fundamental checks', () => {
  it("Testing for 0", () => assert.deepEqual(pyramid(0), []));
  it("Testing for 1", () => assert.deepEqual(pyramid(1), [[1]]));
  it("Testing for two", () => assert.deepEqual(pyramid(2), [[1], [1, 1]]));
  it("Testing for 3", () => assert.deepEqual(pyramid(3), [[1], [1, 1], [1, 1, 1]]));
});
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments