Skip to content

Instantly share code, notes, and snippets.

@BenDMyers
Last active November 29, 2021 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenDMyers/e56a825d178b24f7bbd591d2edc6343b to your computer and use it in GitHub Desktop.
Save BenDMyers/e56a825d178b24f7bbd591d2edc6343b to your computer and use it in GitHub Desktop.
RWC: Phone Number Keypad Combinations
/**
* @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