0

I would like to know how to calculate all possible combinations in a given arraylist? E.g

ArrayList contains following elements {1, 2, 3}. now the following combinations should be generated

{1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}
dansalmo
  • 11,506
  • 5
  • 58
  • 53
smhvrtyj
  • 11
  • 3
  • Is `{}` one of the combinations? – dansalmo Dec 19 '13 at 19:31
  • 1
    Possible duplicate of [Calculating all of the subsets of a set of numbers](http://stackoverflow.com/questions/4640034/calculating-all-of-the-subsets-of-a-set-of-numbers) – Joel Dec 19 '13 at 19:33
  • You'll have more luck searching for an answer using the words _set_, _[power set](http://en.wikipedia.org/wiki/Power_set)_ and _all subsets_. All permutations of a list is all possible arrangements of its elements. And note that a power set would include the empty set. [Here's](http://rosettacode.org/wiki/Power%5FSet#Java) some Java code if you want to implement it yourself. – keyser Dec 19 '13 at 19:33

2 Answers2

1

you can try Guava's Sets#powerSet

Sets.powerSet(Sets.newHashSet(<your list>))

Алексей
  • 1,847
  • 12
  • 15
1

You can see each element in array list as a bit and implement a binary counter . The count gives you all the sets . You have 1, 2 ,3 in arraylist , lets visualize them as 3 bits for a while . 000, 001, 010, 011, 100, 101, 110,111 gives you the power set. All you need to is implement a binary counter , which is trivial.

amrx
  • 673
  • 1
  • 9
  • 23