QuestionAsk Questions?

Posted in : Java Beginners

Hello :)

am a fresher to java

i am in need of a java code which generates the powerset of a given set

i.e

suppose the set S be {a,b,c}

the power set would be

{}

{a}

{b}

{c}

{a,b}

{a,c}

{b,c}

{a,b,c}

and also the size of the set may vary

kindly do the needfull

thanks and regards

Shilpa.R

am a fresher to java

i am in need of a java code which generates the powerset of a given set

i.e

suppose the set S be {a,b,c}

the power set would be

{}

{a}

{b}

{c}

{a,b}

{a,c}

{b,c}

{a,b,c}

and also the size of the set may vary

kindly do the needfull

thanks and regards

Shilpa.R

View Answers

March 5, 2010 at 11:31 AM

Hi Friend,

Try the following code:

import java.util.*;

public class PowerSet{

public static void main(String[] args) {

String st[] = {"a", "b", "c"};

LinkedHashSet hashSet = new LinkedHashSet();

int len = st.length;

int elements = (int) Math.pow(2,len);

for (int i = 0; i < elements; i++) {

String str = Integer.toBinaryString(i);

int value = str.length();

String pset = str;

for (int k = value; k < len; k++) {

pset = "0" + pset;

}

LinkedHashSet set = new LinkedHashSet();

for (int j = 0; j < pset.length(); j++) {

if (pset.charAt(j) == '1')

set.add(st[j]);

}

hashSet.add(set);

}

System.out.println(hashSet.toString());

}

}

Thanks

Try the following code:

import java.util.*;

public class PowerSet{

public static void main(String[] args) {

String st[] = {"a", "b", "c"};

LinkedHashSet hashSet = new LinkedHashSet();

int len = st.length;

int elements = (int) Math.pow(2,len);

for (int i = 0; i < elements; i++) {

String str = Integer.toBinaryString(i);

int value = str.length();

String pset = str;

for (int k = value; k < len; k++) {

pset = "0" + pset;

}

LinkedHashSet set = new LinkedHashSet();

for (int j = 0; j < pset.length(); j++) {

if (pset.charAt(j) == '1')

set.add(st[j]);

}

hashSet.add(set);

}

System.out.println(hashSet.toString());

}

}

Thanks

Related Tutorials/Questions & Answers: