Reputation: 1160
Problem
Write a function that takes in an array of unique integers and returns its powerset. The powerset P(X) of a set X is the set of all subsets of X. For example, the powerset of [1,2] is [[], [1], [2], [1,2]]. Note that the sets in the powerset do not need to be in any particular order.
My approach
My approach is quite simple i will start off with a ArrayList of ArrayList called master . I will create a emptyList and add it to the master. Then i will iterate through each number and for each number i will create a a new list like all the lists in the master already but append the new number to it. so if i have a empty list inside master list and my num is 1 i will add [1] to the master. Then when i am at 2 i will add [2] and [1,2] to the master list.
MY CODE
public static void main(String args[]) {
ArrayList<Integer> inputList = new ArrayList<>();
inputList.add(1);
inputList.add(2);
inputList.add(3);
System.out.println(powerset(inputList).size());
}
public static ArrayList<ArrayList<Integer>> powerset(ArrayList<Integer> array) {
ArrayList<ArrayList<Integer>> master = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> emptyList = new ArrayList<>();
master.add(emptyList);
for(Integer num: array){
for(ArrayList<Integer> list: master){
ArrayList<Integer> toAppendList = list;
toAppendList.add(num);
master.add(toAppendList);
}
}
return master;
}
ISSUE
For some reason i keep getting
Exception in thread "main" java.util.ConcurrentModificationException
I am not sure how this is a concurrent modification and how can i remove it.
Upvotes: 0
Views: 54
Reputation: 46
You are trying to iterate and modify a list at the same time and is not allowed. Also the algorithm is incorrect. You can have a look at a better implementation here Obtaining a powerset of a set in Java :)
Upvotes: 1