Created
March 18, 2021 12:49
-
-
Save christophschubert/6dc01e96afeeed182e7cdc4c7e5ded48 to your computer and use it in GitHub Desktop.
Generate all permutations of Java List. Uses Java 11 var.
This file contains hidden or 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 GeneratePermutations { | |
static <E> List<E> addToCopy(List<E> original, int pos, E e) { | |
final var r = new ArrayList<>(original); | |
r.add(pos, e); | |
return r; | |
} | |
public static <E> List<List<E>> generatePermutations(List<E> original) { | |
if (original.isEmpty()) { | |
return List.of(new ArrayList<>()); | |
} | |
final int size = original.size(); | |
return generatePermutations(original.subList(1, size)).stream().flatMap( | |
s -> IntStream.range(0, size).mapToObj(i -> addToCopy(s, i, original.get(0))) | |
).collect(Collectors.toList()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment