This time, the problem was a little different. Phone keys have certain letters written on them as shown below:

We were to write a function that takes up to four digits of a phone number and return a list of all possible combinations that can be written.

Example:

1 2 3 4 5 6 |
telephoneWords('5872'); => ['JTPA', 'JTPB', 'JTPC', ..., 'LVSC'] |

Armed with the following “help”:

1 2 3 4 5 6 7 8 9 10 11 12 |
var phoneDigitsToLetters = { 0: '0', 1: '1', 2: 'ABC', 3: 'DEF', 4: 'GHI', 5: 'JKL', 6: 'MNO', 7: 'PQRS', 8: 'TUV', 9: 'WXYZ' }; |

I tackled the problem with recursion and came up with the following:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var telephoneWords = function(digitString) { var results = []; // set results equal to empty array var combos = function(digits, wordSoFar) { // walk the tree if (digits.length === 0) { // if done with creating a word results.push(wordSoFar); // push word onto results array and return **BASE CASE** return; } var letters = phoneDigitsToLetters[digits[0]]; // get the first digit from the helper // cycle through the list of letters (ie. 'ABC', 'GHI' or '0') for( var i = 0; i < letters.length; i++ ){ // loop through letters from the helper // recurse on what's left of digitString after removing 'letters' // and the wordSoFar plus the letter...building up the word combos(digits.substr(1), wordSoFar + letters[i]); } }; combos(digitString, ''); // call recursive function with the initial string return results; // return the array of all possible permutations }; |

This is just a simple iteration on my initial post of Counting Leaves and shows how easy recursion can be once you get the hang of it!