Generating desired pairs within a range using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number n. Our function should generate an array containing the pairs of integers [a, b] that satisfy the following conditions −

0 <= a <= b <= n

Example

Following is the code −

 Live Demo

const num = 4;
const findPairs = (n = 1) => {
   const arr = [];
   for(let i = 0; i <= n; i++){
      for(let j = i; j <=n; j++){
         let temp = [];
         temp.push(i, j);
         arr.push(temp);
      };
   };
   return arr;
};
console.log(findPairs(num));

Output

[ [ 0, 0 ],
[ 0, 1 ],
[ 0, 2 ],
[ 0, 3 ],
[ 0, 4 ],
[ 1, 1 ],
[ 1, 2 ],
[ 1, 3 ],
[ 1, 4 ],
[ 2, 2 ],
[ 2, 3 ],
[ 2, 4 ],
[ 3, 3 ],
[ 3, 4 ],
[ 4, 4 ] ]
raja
Published on 21-Apr-2021 10:25:59
Advertisements