Created
September 28, 2012 02:16
-
-
Save linstantnoodles/3797598 to your computer and use it in GitHub Desktop.
cs1 combinations
This file contains 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
/* | |
* Question: Generate all the possible combinations of the letters on the telephone keypads. Recursively. | |
* Basically, the product of N sets. | |
* e.g given 2,3. Valid combinations include (A,D),(A,E),(B,D)... | |
*/ | |
public class KeyPadCombinations { | |
/* | |
* Parameters | |
* numbers = the key pad #s index = the position of a letter for | |
* each number level = the position of the current number | |
*/ | |
public static void combo(int[] numbers, int[] index, int level) { | |
// if we are at the last number | |
if (level == numbers.length - 1) { | |
// for every letter of the number on this level | |
for (int j = 0; j < getLetters(numbers[level]).length; j++) { | |
// print the letter value of the first number up to number at LEVEL. | |
for (int k = numbers.length - 1; k > 0; k--) { | |
System.out.print(getLetters(numbers[level - k])[index[level - k]]); | |
} | |
// print the letter of the current (last) number | |
System.out.print(getLetters(numbers[level])[j]); | |
// create new line | |
System.out.println(); | |
} | |
} else { | |
// if not the last number, save the position of the letter in loop. | |
for (int i = 0; i < getLetters(numbers[level]).length; i++) { | |
index[level] = i; | |
// recursive call on the next number. | |
combo(numbers, index, level + 1); | |
} | |
} | |
} | |
//returns a set of letters in the num set | |
public static String[] getLetters(int num) { | |
String[] keys = new String[4]; | |
String[] two = { "A", "B", "C" }; | |
String[] three = { "D", "E", "F" }; | |
String[] four = { "G", "H", "I" }; | |
String[] five = { "J", "K", "L" }; | |
String[] six = { "M", "N", "O" }; | |
String[] seven = { "P", "Q", "R", "S" }; | |
String[] eight = { "T", "U", "V" }; | |
String[] nine = { "W", "X", "Y", "Z" }; | |
switch (num) { | |
case 2: keys = two; break; | |
case 3: keys = three; break; | |
case 4: keys = four; break; | |
case 5: keys = five; break; | |
case 6: keys = six; break; | |
case 7: keys = seven; break; | |
case 8: keys = eight; break; | |
case 9: keys = nine; break; | |
default: System.out.println("Invalid Number"); break; | |
} | |
return keys; | |
} | |
public static void main(String[] args) { | |
int[] a = { 2, 9, 5, 7, 4, 2, 3 }; | |
int[] index = new int[10]; | |
combo(a, index, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment