Find Number Combinations in JavaScript
What you’ll learn
- How to print all orderings of three numbers using three loops.
- How to print each unordered pair from an array once using
j > i. - Permutation vs combination in simple words.
Overview
This page shows two patterns: permutations of three values (order matters) and pair combinations from four values (order ignored).
Live preview
📜 Pseudocode
Pseudocode
// Permutations of 3 values
for i in 0..2:
for j in 0..2:
for k in 0..2:
if i, j, k are all different:
print arr[i], arr[j], arr[k]
// Combinations of 2 from n
for i in 0..n-2:
for j in i+1..n-1:
print arr[i], arr[j]1
All orderings of three numbers
JavaScript
const arr = [1, 2, 3];
const lines = [];
lines.push("All orderings (permutations) of the three numbers:");
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
for (let k = 0; k < 3; k++) {
if (i !== j && j !== k && i !== k) {
lines.push(arr[i] + " " + arr[j] + " " + arr[k]);
}
}
}
}
console.log(lines.join("\n"));2
All pairs from four numbers
JavaScript
const arr = [10, 20, 30, 40];
const lines = [];
lines.push("All unordered pairs (choose 2 from 4):");
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
lines.push(arr[i] + " " + arr[j]);
}
}
console.log(lines.join("\n"));❓ FAQ
Permutation counts order (1,2,3 differs from 1,3,2). Combination ignores order (pair 10,20 is same as 20,10).
Each loop picks one position in a three-item ordering. Distinct index checks ensure no slot repeats.
It avoids duplicate pairs, so each unordered pair appears exactly once.
Exactly 6, because 3! = 6 permutations.
Yes. If input contains duplicates, printed permutations may look repeated even if indices differ.
Example 1 is constant for fixed size 3. Pair listing is O(n^2) for n items.
⏱️ Time and space complexity
| Program | Time | Extra space |
|---|---|---|
| Permutations for fixed size 3 | O(1) | O(1) |
| All pairs from n values | O(n^2) | O(1) (excluding output) |
Summary
- Permutation: order matters, so three loops with distinct indices.
- Combination pairs: use
j = i + 1to avoid duplicates.
Did you know?
In math, combination usually ignores order, while permutation counts different orders. This page shows both patterns using readable nested loops.
8 people found this page helpful
