patternjavaMinor
Java 8 Stream to produce all permutations of an array using recursion
Viewed 0 times
streamproducerecursionallarrayjavausingpermutations
Problem
I want to write a class that returns a Stream of permutations of an
Problem with my solution is that it is nesting a lot of Streams with concat, many of them being just empty ones. Another issue is that it creates all permutations before returning the Stream, so it not really streaming... :- )
I saw Minborg's solution, but I wanted to make something simpler, here based on Sedgewick and Wayne's algorithm.
Can above code be improved?
int[].public class Permutations {
public static Stream of(int[] array) {
return permute(array, array.length);
}
public static Stream permute(int[] array, int n) {
if (n == 1) {
return Stream.of(Arrays.copyOf(array, array.length));
} else {
Stream tmp = Stream.empty();
for (int i = 0; i < n; i++) {
swap(array, i, n - 1);
tmp = Stream.concat(permute(array, n - 1), tmp);
swap(array, i, n - 1);
}
return tmp;
}
}
private static void swap(int[] a, int i, int j) {
if (i != j) {
int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
}
}
}Problem with my solution is that it is nesting a lot of Streams with concat, many of them being just empty ones. Another issue is that it creates all permutations before returning the Stream, so it not really streaming... :- )
I saw Minborg's solution, but I wanted to make something simpler, here based on Sedgewick and Wayne's algorithm.
Can above code be improved?
Solution
Not a review, but an extended comment:
I strongly advise against recursion here. The permutations have a natural (lexicographic) ordering, and given a permutation it is easy to construct a next one.
This hints that to achieve true streaming: implement
I strongly advise against recursion here. The permutations have a natural (lexicographic) ordering, and given a permutation it is easy to construct a next one.
This hints that to achieve true streaming: implement
nextPermutation() method, and pass it to Stream.iterate() as an unary operator.Context
StackExchange Code Review Q#123710, answer score: 5
Revisions (0)
No revisions yet.