Posted By

edwarddr on 05/22/12


Tagged

problem quiz


Versions (?)

SubsetGenerator


 / Published in: Java
 

A short java sample of generating all the possible subset given a list.

  1. import java.util.ArrayList;
  2.  
  3. class SubsetGenerator
  4. {
  5.  
  6. public SubsetGenerator()
  7. {
  8.  
  9. }
  10.  
  11. // starting index assumed to be 0
  12. public void generate(char[] input, int index, ArrayList<String> holder)
  13. {
  14. if (index < 0)
  15. return;
  16.  
  17. if (index >= input.length)
  18. {
  19. if (holder != null)
  20. {
  21. printOut(holder);
  22. }
  23. return;
  24. }
  25.  
  26. ArrayList<String> branchOut = (ArrayList<String>) holder.clone();
  27. branchOut.add(String.valueOf(input[index]));
  28. generate(input, index+1, holder);
  29. generate(input, index+1, branchOut);
  30. }
  31.  
  32. private void printOut(ArrayList<String> holder)
  33. {
  34. if (holder.size() == 0)
  35. {
  36. System.out.println("This subset contains: Empty Set!");
  37. return;
  38. }
  39. System.out.print("This subset contains: ");
  40. for (int i = 0; i < holder.size(); i++)
  41. {
  42. System.out.print(holder.get(i) + " ");
  43. }
  44. System.out.println();
  45. }
  46.  
  47. public static void main(String args[])
  48. {
  49. char[] sample = {'a','b','c','d'};
  50. SubsetGenerator tester = new SubsetGenerator();
  51. tester.generate(sample, 0, new ArrayList<String>());
  52. }
  53. }

Report this snippet  

You need to login to post a comment.