All upper and lower case permutations of a string
Write a method that takes a string and returns every possible combination of upper and lower case letters for that string. For instance, cat would return:
cat caT cAt cAT Cat CaT CAt CAT
Answer:
1)
Well, you know ahead of time that for a 6 letter word, you have 2^6 = 64 possibilities. You could have the function return an array of Strings. Have a loop that goes from 0 to 63 (or 127, 255, etc.). For your example, "cat", it would be 0 to 7, so you'd need an array of size 8. For the 5th element of the array, take the loop counter variable value (in this case, 5) and convert to binary (no converting needed really, since it's stored that way).
5 is equivalent to 101 in binary.
Integer.toBinaryString(int i)
Let 1 be upper case, let 0 be lower case.
So the fifth element in the array would be CaT.
Go through the loop (0 to 7) and you'll get all possibilities by iterating through the binary ints.
void printPermutations(String text) { char[] chars = text.toCharArray(); for (int i = 0, n = (int) Math.pow(2, chars.length); i < n; i++) { char[] permutation = new char[chars.length]; for (int j =0; j < chars.length; j++) { permutation[j] = (isBitSet(i, j)) ? Character.toUpperCase(chars[j]) : chars[j]; } System.out.println(permutation); } } boolean isBitSet(int n, int offset) { return (n >> offset & 1) != 0; }
2)
public static void comb4(String word) { comb4(word,new char[word.length()],0); } private static void comb4(String word, char[] accu, int index) { if(index == word.length()) { System.out.println(accu); } else { char ch = word.charAt(index); accu[index] = Character.toLowerCase(ch); comb4(word, accu , index+1); accu[index] = Character.toUpperCase(ch); comb4(word, accu, index+1); } }















