-
-
Save felipeg48/7fe273bbb7e3193cf069f2592d456ef0 to your computer and use it in GitHub Desktop.
Find all permutations of given items using Java 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Permutations { | |
public static <T> Stream<Stream<T>> of(final List<T> items) { | |
return IntStream.range(0, factorial(items.size())).mapToObj(i -> permutation(i, items).stream()); | |
} | |
private static int factorial(final int num) { | |
return IntStream.rangeClosed(2, num).reduce(1, (x, y) -> x * y); | |
} | |
private static <T> List<T> permutation(final int count, final LinkedList<T> input, final List<T> output) { | |
if (input.isEmpty()) { return output; } | |
final int factorial = factorial(input.size() - 1); | |
output.add(input.remove(count / factorial)); | |
return permutation(count % factorial, input, output); | |
} | |
private static <T> List<T> permutation(final int count, final List<T> items) { | |
return permutation(count, new LinkedList<>(items), new ArrayList<>()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment