-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathletterCombinationPhoneNumber.js
More file actions
52 lines (44 loc) · 1.27 KB
/
letterCombinationPhoneNumber.js
File metadata and controls
52 lines (44 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const phoneDigitsMap = {
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z']
}
//letter combination phone number
/**
* @param {string} digits
* @return {string[]}
*/
const letterCombinations = function(digits) {
const combinations = []
if (!digits.length) {
return []
}
const possibleLetters = digits.split('').map(digit => phoneDigitsMap[digit])
let temp = []
for (let i = 0; i < possibleLetters[0].length; i++) {
temp = possibleLetters[0][i]
const bt = generateCombinations(temp, possibleLetters, 1)
combinations.push(bt)
}
return combinations.flat(digits.length - 1)
};
const generateCombinations = (original, combinations, currentIndex) => {
if (currentIndex === combinations.length) {
return original
}
const results = []
const tmp = []
combinations[currentIndex].forEach(option => tmp.push(`${original}${option}`))
tmp.forEach(result => {
const bt = generateCombinations(result, combinations, currentIndex + 1)
results.push(bt)
})
return results
}
const example = '2345'
console.log(letterCombinations(example))