Facebook Interview Question
Country: United States
In Scala:
object Main {
val mapping = Map(1 -> "ABC", 2 -> "DEF")
def main(args: Array[String]): Unit = {
val a = mapping.keySet.toArray
var c = Array.ofDim[Char](a.length)
printCombos(a, 0, c)
}
def printCombos(a:Array[Int], i:Int, c:Array[Char]) : Unit = {
if (i == a.length) {
c foreach print
println
} else if (i < a.length) {
var j = 0
for (j <- 0 to mapping(a(i)).length() - 1) {
c(i) = mapping(a(i)).charAt(j)
printCombos(a, i + 1, c)
}
}
}
}
// output:
/*
AD
AE
AF
BD
BE
BF
CD
CE
CF
*/
This is how you do it - in a fully declarative paradigm.
__mapping__ = {
1 : [ 'A', 'B', 'C' ], 2 : [ 'D', 'E', 'F' ],
3 : [ 'G', 'H', 'I' ], 4 : [ 'J', 'K', 'L' ],
5 : [ 'M', 'N', 'O' ], 6 : [ 'P', 'Q', 'R' ],
7 : [ 'S', 'T', 'U' ], 8 : [ 'V', 'W', 'X' ],
9 : ['Y', 'Z'] }
def map_back(n){
args = list( str(n).value ) as { __mapping__[int($.o)] }
join(@ARGS = args ) where { true } as { str($.o,'') }
}
println(map_back(12))
The result:
zmb tmp.zm
[ AD,AE,AF,BD,BE,BF,CD,CE,CF ]
void Combs(unordered_map<char, vector<char>> &map, string const &digits,
vector<string> &combs, string const comb = "")
{
if (comb.size() == digits.size()) {
if (!comb.empty()) {
combs.push_back(comb);
}
return;
}
int digit_idx = comb.size();
char digit = digits[digit_idx];
auto it = map.find(digit);
if (it != map.end()) {
vector<char> const &letters = it->second;
for (char c : letters) {
Combs(map, digits, combs, comb + c);
}
}
}
def findcombination(self, s):
d={'1':'','2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz','10':''}
value_list = list()
if len(s) == 0:
return []
result = [""]
for digit in s:
value_list=d[digit]
for i in value_list:
out=[]
for j in result:
out.append(i+j)
result=out
return result
Working code
- syam.bollu May 09, 2017