Advertisement
burke

Generating all combinations of multiple lists

Apr 8th, 2018
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1. // Adapted from https://stackoverflow.com/a/23870892/5602641
  2.  
  3. public static <T> Collection<List<T>> permutations(List<Collection<T>> collections) {
  4.   if (collections == null || collections.isEmpty()) {
  5.     return Collections.emptyList();
  6.   } else {
  7.     Collection<List<T>> output = new LinkedList<T>();
  8.     recursePermutations(collections, output, 0, new LinkedList<T>());
  9.     return output;
  10.   }
  11. }
  12.  
  13. private static <T> void recursePermutations(List<Collection<T>> source, Collection<List<T>> output, int depth, List<T> current) {
  14.   if (depth == source.size()) {
  15.     output.add(current);
  16.     return;
  17.   }
  18.  
  19.   Collection<T> currentCollection = source.get(depth);
  20.   for (T element : currentCollection) {
  21.     List<T> copy = new LinkedList<T>(current);
  22.     copy.add(element);
  23.     recursePermutations(source, output, depth+1, copy);
  24.   }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement