Last active
November 29, 2021 06:31
-
-
Save BenDMyers/e56a825d178b24f7bbd591d2edc6343b to your computer and use it in GitHub Desktop.
RWC: Phone Number Keypad Combinations
This file contains hidden or 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
/** | |
* @type {Object<String, String[]>} | |
*/ | |
const keypad = { | |
'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'] | |
}; | |
/** | |
* Recursively determines possible keypad combinations of a given string of digits | |
* @param {string} digits - a string containing only digits from 2 to 9 | |
* @returns {string[]} all possible letters that could be made on the keypad with `digits` | |
*/ | |
function phoneNumbers(digits) { | |
// Base case | |
if (digits.length === 1) { | |
return keypad[digits]; | |
} | |
// Recursive case | |
const firstDigit = digits.charAt(0); | |
const tail = digits.substr(1); | |
const tailCombinations = phoneNumbers(tail); | |
const combinations = []; | |
for (const possibleCharacter of keypad[firstDigit]) { | |
for (const tailCombination of tailCombinations) { | |
combinations.push(possibleCharacter + tailCombination); | |
} | |
} | |
return combinations; | |
} | |
console.log(phoneNumbers('23')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment