Last active
December 13, 2015 20:18
-
-
Save charlespunk/4968828 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Write a method to return all subsets of a set. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//recursive | |
public static ArrayList<ArrayList<Character>> findSubsets(char[] input){ | |
ArrayList<ArrayList<Character>> listOfSubsets= new ArrayList<ArrayList<Character>>(); | |
listOfSubsets.add(new ArrayList<Character>()); | |
findSubsets(input, 0, listOfSubsets); | |
return listOfSubsets; | |
} | |
public static void findSubsets(char[] input, int index, ArrayList<ArrayList<Character>> listOfSubsets){ | |
if(index >= input.length) return; | |
ArrayList<ArrayList<Character>> newListOfSubsets = new ArrayList<ArrayList<Character>>(); | |
for(ArrayList<Character> subset : listOfSubsets){ | |
ArrayList<Character> newSubset = new ArrayList<Character>(); | |
newSubset.addAll(subset); | |
newSubset.add(input[index]); | |
newListOfSubsets.add(newSubset); | |
} | |
listOfSubsets.addAll(newListOfSubsets); | |
findSubsets(input, index + 1, listOfSubsets); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//binary | |
public static ArrayList<ArrayList<Character>> findSubsets(char[] input){ | |
ArrayList<ArrayList<Character>> listOfsubsets = new ArrayList<ArrayList<Character>>(); | |
int num = 1 << input.length; | |
for(int i = 0; i < num; i++) listOfsubsets.add(getSubsetFromBinary(i, input)); | |
return listOfsubsets; | |
} | |
public static ArrayList<Character> getSubsetFromBinary(int i, char[] input){ | |
ArrayList<Character> thisSubset = new ArrayList<Character>(); | |
for(int index = 0; i != 0; i >>= 1, index++) if((i & 1) != 0) thisSubset.add(input[index]); | |
return thisSubset; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment