Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. [[1,2]] == [[2,1]]
  2. [[1],[2]] == [[2],[1]]
  3. [[1,2],[3,4]] == [[2,1],[4,3]] == [[4,3],[2,1]]...
  4.  
  5. [[1,2]]
  6. [[1],[2]]
  7.  
  8. [[1,2,3]]
  9. [[1,2],[3]]
  10. [[1,3],[2]]
  11. [[2,3],[1]]
  12. [[1],[2],[3]]
  13.  
  14. [[1,2,3,4]]
  15. [[1,2,3],[4]]
  16. [[1,2,4],[3]]
  17. [[1,3,4],[2]]
  18. [[2,3,4],[1]]
  19. [[1,2],[3,4]] <= Equivalent to [[3,4],[1,2]]
  20. [[1,3],[2,4]] <= Equivalent to [[2,4],[1,3]]
  21. [[1,4],[2,3]] <= Equivalent to [[2,3],[1,4]]
  22. [[1,2],[3],[4]]
  23. [[1,3],[2],[4]]
  24. [[1,4],[2],[3]]
  25. [[2,3],[1],[4]]
  26. [[2,4],[1],[3]]
  27. [[3,4],[1],[2]]
  28. [[1],[2],[3],[4]]
  29.  
  30. public Set<Set<Set<Integer>>> recurseGroups(List<Integer> initialArray, List<Set<Integer>> currentGroups, int i) {
  31. if (i == initialArray.size()) {
  32. // Deep copy current group to save its content
  33. Set<Set<Integer>> copy = currentGroups.stream()
  34. .map(HashSet::new)
  35. .collect(Collectors.toSet());
  36.  
  37. return Collections.singleton(copy);
  38. }
  39.  
  40. Set<Set<Set<Integer>>> result = new HashSet<>();
  41.  
  42. for (int j = i; j < initialArray.size(); ++j) {
  43. // Add a singleton group with the i-th integer
  44. // And generate groups with the remaining elements
  45. Set<Integer> newGroup = new HashSet<>(Collections.singletonList(initialArray.get(i)));
  46. currentGroups.add(newGroup);
  47. result.addAll(recurseGroups(initialArray, currentGroups, i + 1));
  48. currentGroups.remove(newGroup);
  49.  
  50. // Add the i-th integer to each previous existing groups
  51. // And generate groups with the remaining elements
  52. for (int k = 0; k < currentGroups.size(); ++k) {
  53. currentGroups.get(k).add(initialArray.get(i));
  54. result.addAll(recurseGroups(initialArray, currentGroups, i + 1));
  55. currentGroups.get(k).remove(initialArray.get(i));
  56. }
  57. }
  58.  
  59. return result;
  60. }
  61.  
  62. // Calling line
  63. Set<Set<Set<Integer>>> groups = recurseGroups(Arrays.asList(1,2,3), new ArrayList<>(), 0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement