Facebook Interview Question
Software Engineer / Developerspublic class Phone2Text {
private static String[] mapping = { "ABC", "DEF", "GHI", "JKL", "MNO",
"PQR", "STU", "VW", "XY", "Z*#" };
public static void combinations(int[] number, char[] buf, int numIndex) {
for (int i = 0; i < mapping[number[numIndex]].length(); i++) {
buf[numIndex] = mapping[number[numIndex]].charAt(i);
if (numIndex < number.length - 1) {
combinations(number, buf, numIndex + 1);
} else
System.out.println(buf);
}
}
public static void main(String[] args) {
int num[] = { 5, 8, 5, 5, 0, 3, 3, 4, 4, 7 };
Phone2Text.combinations(num, new char[num.length], 0);
}
}
<pre lang="" line="1" title="CodeMonkey23618" class="run-this">import Data.Array (listArray, (!))
import Data.Char (digitToInt)
import Data.Set (fromList, member)
keyMap = listArray (2, 9) ["ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"]
digitCombinations digits = sequence $ [keyMap ! i | i <- digits]
dictionary = fromList ["DOG", "CAT", "BIRD", "REPTILE"]
main = do
numberString <- getLine
let numberCombinations = digitCombinations $ map digitToInt numberString
return $ filter ((flip member) dictionary) numberCombinations
</pre><pre title="CodeMonkey23618" input="yes">
</pre>
string lookup[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int coi(char c){
return ((int)c - 48);
}
void print(string oldString, string newString)
{
if (oldString.length() == 0) {
cout << newString << endl;
return;
}
else {
string characters = lookup[coi(oldString[0])];
int numOfChars = characters.length();
for(int i=0; i<numOfChars; ++i)
{
print(oldString.substr(1),newString+characters[i]);
}
}
}
For 1st part:
- bebo October 20, 2010If one digit represents 3 letters. So, 4 digit will represent 3^4 combinations of strings. We can do that in a for loop ?
For 2nd part:
After getting output from 1st part, we can check if (combination present in dict. ) ?
and output accordingly. ?