Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find all permutations of given items using Java 8
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<>());
}
}
@jaycobbcruz

This comment has been minimized.

Copy link
Owner Author

@jaycobbcruz jaycobbcruz commented Apr 30, 2017

Permutations.of(Arrays.asList(1, 2, 3)).forEach(p -> { p.forEach(System.out::print); System.out.print(" "); });

will return:
123 132 213 231 312 321

@1ALL1

This comment has been minimized.

Copy link

@1ALL1 1ALL1 commented Apr 26, 2019

Hey, can you please tell me which packages I have to include? It does´nt run on my Java.

@rokkbert

This comment has been minimized.

Copy link

@rokkbert rokkbert commented May 10, 2019

import java.util.stream.*;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.