As you probably already know, the number of possible different combinations is 2 ^ n, where n is equal to the length of the input string.
Since n can theoretically be quite large, it is likely that 2 ^ n will exceed the capacity of a primitive type such as int. (The user may have to wait a few years for all combinations to finish printing, but this is their business.)
Instead, use bit-bit to save all possible combinations. We set the number of bits to n and initialize them all to 1. For example, if the input string is "abcdefghij", the initial values โโof the bit vector will be {1111111111}.
For each combination, we just have to scroll through all the characters in the input line and set each of them to uppercase if the corresponding bit is 1, otherwise set it to lowercase. Then we reduce the bit vector and repeat.
For example, the process would look like this for entering "abc":
Bits: Matching Combo:
111 ABC
110 ABc
101 AbC
100 abc
011 AbC
010 AbC
001 AbC
000 a
By using a loop rather than calling a recursive function, we also avoid throwing exceptions on large input strings.
Here is the real implementation:
import java.util.BitSet; public void PrintCombinations(String input) { char[] currentCombo = input.toCharArray(); // Create a bit vector the same length as the input, and set all of the bits to 1 BitSet bv = new BitSet(input.length()); bv.set(0, currentCombo.length); // While the bit vector still has some bits set while(!bv.isEmpty()) { // Loop through the array of characters and set each one to uppercase or lowercase, // depending on whether its corresponding bit is set for(int i = 0; i < currentCombo.length; ++i) { if(bv.get(i)) // If the bit is set currentCombo[i] = Character.toUpperCase(currentCombo[i]); else currentCombo[i] = Character.toLowerCase(currentCombo[i]); } // Print the current combination System.out.println(currentCombo); // Decrement the bit vector DecrementBitVector(bv, currentCombo.length); } // Now the bit vector contains all zeroes, which corresponds to all of the letters being lowercase. // Simply print the input as lowercase for the final combination System.out.println(input.toLowerCase()); } public void DecrementBitVector(BitSet bv, int numberOfBits) { int currentBit = numberOfBits - 1; while(currentBit >= 0) { bv.flip(currentBit); // If the bit became a 0 when we flipped it, then we're done. // Otherwise we have to continue flipping bits if(!bv.get(currentBit)) break; currentBit--; } }
Kevin D.
source share