Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generating desired pairs within a range using JavaScript
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
This means we need to find all possible pairs where the first number is less than or equal to the second number, and both numbers are within the range from 0 to n (inclusive).
Algorithm Approach
The solution uses nested loops where:
- The outer loop iterates from 0 to n (for the first element 'a')
- The inner loop starts from 'i' and goes to n (for the second element 'b')
- This ensures a ? b condition is always maintained
Example
Following is the complete implementation:
const num = 4;
const findPairs = (n = 1) => {
const arr = [];
for(let i = 0; i
[
[ 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 ]
]
Optimized Version
Here's a more concise version using array literals directly:
const findPairsOptimized = (n = 1) => {
const result = [];
for(let i = 0; i
[
[ 0, 0 ],
[ 0, 1 ],
[ 0, 2 ],
[ 0, 3 ],
[ 1, 1 ],
[ 1, 2 ],
[ 1, 3 ],
[ 2, 2 ],
[ 2, 3 ],
[ 3, 3 ]
]
How It Works
For n = 4, the algorithm generates:
- i = 0: pairs [0,0], [0,1], [0,2], [0,3], [0,4]
- i = 1: pairs [1,1], [1,2], [1,3], [1,4]
- i = 2: pairs [2,2], [2,3], [2,4]
- i = 3: pairs [3,3], [3,4]
- i = 4: pair [4,4]
The total number of pairs generated for any n is (n+1)(n+2)/2, which represents the number of combinations with repetition allowed.
Conclusion
This nested loop approach efficiently generates all valid pairs where a ? b within the given range. The time complexity is O(n²) and space complexity is O(n²) for storing the result.
