Java Program to find Subsets of a Set

               Set has a collections of elements. Sub set contains the combinations of elements. It can be done by bit manipulation or recursion.

Java implementation:

  • It starts with including the built in packages java.util.ArrayList and java.util.List.
  • A public class is created with main ().
  • A integer array is assigned with elements.
  • A subset is developed as list. Let us call the findSubset() function to get the subsets.
  • ‘findSubset()’ – This function creates the subsets of the given set.
  • Finally, it prints the sub sets.

Technical information:

Class name: SubsetFinderEg

Variables:

set1 as integer array.

subset1 as integer list.

Index as integer

‘all_Subsets, ‘new_Subset’,’more_Subsets’ as array list.

S_item as integer.

Member function: findSubset().

Program:

//include the built-in packages.

import java.util.ArrayList;

import java.util.List;

//class creation with main() class

public class SubsetFinderEg {

    public static void main(String[] args) {

        int[] set1 = {4, 2, 5}; //elements assignement

        List<List<Integer>> subset1 = findSubset(set1, 0);

        System.out.println(subset1);

    }

    public static List<List<Integer>> findSubset(int[] set1, int index) {

        List<List<Integer>> all_Subsets;

        if (index == set1.length) {

            all_Subsets = new ArrayList<>();

            all_Subsets.add(new ArrayList<>()); // insert empty set

        } else {

            all_Subsets = findSubset(set1, index + 1);

            int s_item = set1[index];

            List<List<Integer>> moreSubsets = new ArrayList<>();

            for (List<Integer> subset : all_Subsets) {

                List<Integer> new_Subset = new ArrayList<>(subset);

                new_Subset.add(s_item);

                moreSubsets.add(new_Subset);

            }

            all_Subsets.addAll(moreSubsets);

        }

        return all_Subsets;

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac SubsetFinderEg.java

C:\raji\blog>java SubsetFinderEg

[[], [5], [2], [5, 2], [4], [5, 4], [2, 4], [5, 2, 4]]

Yes. That’s the output.

Here the set has 3 elements [4,2,5]

The sub sets are [], each element separately [2],[4],[5], combination of two elements [5,2],[5,4],[2,4] and finally all number combinations [5,2,4].

This is the way of creating subsets from a set using java. Hope,this code will useful to you. Keep Coding!!!!

No comments:

Post a Comment