Generating desired pairs within a range using JavaScript


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 ] ]

Updated on: 21-Apr-2021

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements