Skip to content

Instantly share code, notes, and snippets.

@aaiezza
Created March 7, 2021 21:04
Show Gist options
  • Save aaiezza/31edc1290d920b370458219939cb35ab to your computer and use it in GitHub Desktop.
Save aaiezza/31edc1290d920b370458219939cb35ab to your computer and use it in GitHub Desktop.
Algorithm for iterating through combinations of numbers
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CombinationGetter {
public List<int[]> getCombinations(final int n, final int min, final int k) {
final List<int[]> list = new ArrayList<>();
int temp;
final int[] a = new int[n];
Arrays.fill(a, min);
a[n - 1] = 0;
temp = n - 1;
while (true) {
if (a[temp] == k) {
temp--;
if (temp < 0) break;
} else {
a[temp]++;
while (temp + 1 < n) {
temp++;
a[temp] = 1;
}
list.add(Arrays.copyOf(a, n));
}
}
return list;
}
public static void main(final String... args) {
System.out.println("Ciao Mondo!");
final CombinationGetter comboGetter = new CombinationGetter();
System.out.println(
comboGetter
.getCombinations(4, 1, 6)
.stream()
.map(Arrays::toString)
.collect(Collectors.joining("\n")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment