Skip to content

Instantly share code, notes, and snippets.

@bennettdams
Created April 30, 2019 10:57
Show Gist options
  • Save bennettdams/79f69057a15673a1bda16ec3628981ad to your computer and use it in GitHub Desktop.
Save bennettdams/79f69057a15673a1bda16ec3628981ad to your computer and use it in GitHub Desktop.
Generate non-repetetive permutations of given numbers and utilize each combination. Example result for 4: 4! = 24 combinations
import java.util.*;
class Permutations {
public static void main(final String[] args) {
// Permutations of the numbers 0 to 3 to get all possible combinations.
// For 4 numbers the result should be 4! = 24 different combinations
// like 1-2-3-4, 1-2-4-3, 1-3-2-4, 1-3-4-2, etc.
Collection<List<Integer>> permutations = new Permutations()
.generatePermutationsWithoutRepetition(new HashSet<>(Arrays.asList(0, 1, 2, 3)));
permutations.forEach(perm -> {
System.out.println(perm.get(0));
System.out.println(perm.get(1));
System.out.println(perm.get(2));
System.out.println(perm.get(3));
});
}
public <T> Collection<List<T>> generatePermutationsWithoutRepetition(Set<T> availableNumbers) {
Collection<List<T>> permutations = new HashSet<>();
for (T number : availableNumbers) {
Set<T> numbers = new HashSet<>(availableNumbers);
numbers.remove(number);
if (!numbers.isEmpty()) {
Collection<List<T>> childPermutations = generatePermutationsWithoutRepetition(numbers);
for (List<T> childPermutation : childPermutations) {
List<T> permutation = new ArrayList<>();
permutation.add(number);
permutation.addAll(childPermutation);
permutations.add(permutation);
}
} else {
List<T> permutation = new ArrayList<>();
permutation.add(number);
permutations.add(permutation);
}
}
return permutations;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment