x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 1292

# Create a powerset in Java

Hi,

In Java I want to create a powerset, when i give  a set and a number for the size for e.g.

{1,2,3,4} set:3
------------------
{1,2,3}
{1,2,4}
{1,3,4}
{2,3,4}

or
{1,2,3} set 2
{1,2}
{1,3}
{2,3}

thanks
0
kimia_az
• 4
2 Solutions

Commented:
0

Commented:
This implementation is for all sets, I guess it is easy to modify only limiting to
certain size
0

Commented:
0

Commented:

This will print only sets of 2 out of {1,2,3}

``````import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetUtils {
public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
Set<Set<T>> sets = new HashSet<Set<T>>();
if (originalSet.isEmpty()) {
return sets;
}
List<T> list = new ArrayList<T>(originalSet);
Set<T> rest = new HashSet<T>(list.subList(1, list.size()));
for (Set<T> set : powerSet(rest)) {
Set<T> newSet = new HashSet<T>();

}

return sets;
}

public static void main(String[] args){
Set<Integer> mySet = new HashSet<Integer>();
for (Set<Integer> s : SetUtils.powerSet(mySet)) {
if(s.size() == 2)
System.out.println(s);
}

}
}
``````
0

Commented:

This will print only sets of 3 out of {1,2,3,4}  a little bit nicer:

``````import java.util.*;

public class SetUtils {
public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
Set<Set<T>> sets = new HashSet<Set<T>>();
if (originalSet.isEmpty()) {
return sets;
}
List<T> list = new ArrayList<T>(originalSet);
Set<T> rest = new HashSet<T>(list.subList(1, list.size()));
for (Set<T> set : powerSet(rest)) {
Set<T> newSet = new HashSet<T>();

}

return sets;
}

public static <T> Set<Set<T>> powerSet1( Set<T>mySet, int n){
Set<Set<T>> sets1 = new  HashSet<Set<T>>();
Set originalSet =  SetUtils.powerSet(mySet);
Iterator it = originalSet.iterator();
while(it.hasNext()) {
Set s = (Set) it.next();
}

return sets1;
}

public static void main(String[] args){
Set<Integer> mySet = new HashSet <Integer>();
for (Set <Integer> s : SetUtils.powerSet1(mySet, 3)) {
System.out.println(s);
}

}
}
``````
0

Commented:
``````int setLength = 3;
int[] array = new int[]{1,2,3,4};
for(int i=0;i<array.length-2;i++)
{
for(int j=i+1;j<array.length -1;j++)
{
for(int k=j+1;k<array.length;k++)
{
int[] temp = new int[setLength];
temp[0] = array[i];
temp[1] = array[j];
temp[2] = array[k];

System.out.println(temp[0]+","+temp[1]+","+temp[2]);
}
}
}
``````
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.