Guest User

Untitled

a guest
Feb 18th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. package com.tvidushi1.arrays;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7. public class Powerset {
  8.  
  9. public static void main(String[] args) {
  10. List <Object> list = new ArrayList<Object>();
  11. list.add("a");
  12. list.add("b");
  13. list.add("c");
  14.  
  15. System.out.println(getSubsetUsingBitMap(list));
  16. }
  17.  
  18. private static Set<Set<Object>> getSubsetUsingBitMap(List<Object> list){
  19.  
  20. Set<Set<Object>> result = new HashSet<Set<Object>>();
  21.  
  22. int numOfSubsets = 1 << list.size(); //OR Math.pow(2, list.size())
  23.  
  24. // For i from 0 to 7 in case of [a, b, c],
  25. // we will pick 0(0,0,0) and check each bits to see any bit is set,
  26. // If set then element at corresponding position in a given Set need to be included in a subset.
  27. for(int i = 0; i < numOfSubsets; i++){
  28.  
  29. Set<Object> subset = new HashSet<Object>();
  30.  
  31. int mask = 1; // we will use this mask to check any bit is set in binary representation of value i.
  32.  
  33. for(int k = 0; k < list.size(); k++){
  34. System.out.println("mask is "+mask);
  35. if((mask & i) != 0){ // If result is !=0 (or >0) then bit is set.
  36. subset.add(list.get(k)); // include the corresponding element from a given set in a subset.
  37. }
  38.  
  39. // check next bit in i.
  40. mask = mask << 1;
  41. }
  42.  
  43. // add all subsets in final result.
  44. System.out.println(subset);
  45. result.add(subset);
  46. }
  47. return result;
  48. }
  49.  
  50. }
Add Comment
Please, Sign In to add comment