List of correct words from phone mapping

I recently returned from an interview, and they basically asked: given the list of correct words and matching numbers with letters - something like 1 → ABC, 2-> DEF - how would I write a function that returns a list of valid strings. I tried my best and looked for guidance.

function validWords(digits, listOfValidWords) {

}

// for example
var dictionary = [//some list of words];
var words = validWords("1456", dictionary)
+4
source share
1 answer

You can use a combinational algorithm.

var dictionary = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz' },
    number = '345',
    result = [...number]
        .map(n => [...dictionary[n]])
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => v + w)), []));
        
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run code
+4
source

Source: https://habr.com/ru/post/1685776/


All Articles