Find Number Combinations in Java
What you’ll learn
- How to generate all orderings of three numbers using distinct loop indices.
- How to generate unique unordered pairs using
j = i + 1. - When order matters (permutations) vs when it does not (combinations).
Prerequisites
- Basic Java loops, arrays, and conditions.
- Comfort with integer input/output.
The idea
Generate combinations by looping through indices in a controlled way. Distinct-index triple loops produce orderings; j = i + 1 produces unique pairs.
Live preview
Algorithm
Use index loops to generate either all distinct orderings or unique unordered pairs.
📜 Pseudocode
for i in 0..2:
for j in 0..2:
for k in 0..2:
if all distinct: print a[i], a[j], a[k]
for i in 0..n-2:
for j in i+1..n-1:
print a[i], a[j]All orderings of three numbers
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println("All orderings (permutations):");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
if (i != j && j != k && i != k) {
System.out.println(arr[i] + " " + arr[j] + " " + arr[k]);
}
}
}
}
}
}All pairs from four numbers
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
System.out.println("All unordered pairs:");
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
System.out.println(arr[i] + " " + arr[j]);
}
}
}
}Optimization notes
Keep it simple. Prefer clear loops before micro-optimization.
Avoid duplicates. For pairs, start second index at i + 1.
❓ FAQ
🔄 Input / output examples
Input: 1, 2, 3 for permutations and [10,20,30,40] for pairs. Output should list all valid combinations without missing/extra lines.
Edge cases
Repeated values
Decide if repeated output lines are acceptable when values repeat.
Small arrays
No pairs exist for arrays with fewer than 2 elements.
⏱️ Time and space complexity
Pairs from n values: O(n^2). Triple nested index loops: O(n^3).
Summary
- Use loop-index patterns to generate combinations cleanly.
- Use distinct-index checks for orderings.
- Use
j = i + 1for unique pairs.
Permutation means order matters; combination means order does not matter. This page demonstrates both with simple loops.
8 people found this page helpful
