-2

Consider an array of characters characterArray={a,b,c,d}. I want to create a list that contains all possible combination of elements as a Set. For example

Set 1 ={}
Set 2 = {a}
Set 3 = {b}
Set 4 = {c}
Set 5 = {a,b}
Set 6 ={a,c}
......
......
Set N = {a,b,c,d}

After generating all possible combination of sets above. I want to add all the above generated sets into a list (List).

Below is the sample code written

public class CreateSets {

    char a[] = { 'a', 'b', 'c', 'd' };
    List<HashSet> setList = new ArrayList<HashSet>();

    public void createSubsets() {
        for (int i = 0; i < a.length; i++) {
            HashSet temp = new HashSet();
            for (int j = i; j < a.length; j++) {
                temp.add(a[j]);
            }
            setList.add(temp);
        }

    }
    public static void main(String[] args) {
        CreateSets cr = new CreateSets();
        cr.createSubsets();
        System.out.println(cr.setList);
    }

} 
Joe C
  • 15,324
  • 8
  • 38
  • 50
Raghu
  • 33
  • 8

1 Answers1

1
private List<HashSet<Character>> createSubsets(char[] a) {
        List<HashSet<Character>> tempListList = new ArrayList<HashSet<Character>>();
        if (a.length == 0) {
            HashSet<Character> temp = new HashSet<Character>();
            //temp.add(' ');
            tempListList.add(temp);
            return tempListList;
        }
        char tempChar = a[a.length-1];
        List<HashSet<Character>> setList = createSubsets(Arrays.copyOf(a, a.length-1));
        for (HashSet<Character> charSet : setList) {
            HashSet<Character> tempSet = new HashSet<>(charSet);
            tempSet.add(tempChar);
            tempListList.add(tempSet);
        }
        setList.addAll(tempListList);
        return setList;
    }
gati sahu
  • 2,576
  • 2
  • 10
  • 16