I want to write a class that returns a Stream of permutations of an int[]
.
public class Permutations { public static Stream<int[]> of(int[] array) { return permute(array, array.length); } public static Stream<int[]> 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?