I'm trying to get better at Mathematica and in the book I'm using (by Nancy Blachman) is the following question (which apparently was taken from another book: The Art and Science of C) which reads:
On a standard telephone keypad, the digits are mapped onto the alphabet (minus the letters Q and Z) as shown below:
ABC DEF
1 2 3
GHI JKL MNO
4 5 6
PRS TUV WXY
7 8 9
Write a function phoneSpell
that generates all possible letter combinations that correspond to a given
number, represented as a string of digits. For example, if you call phoneSpell[652]
, your function
should generate the 27 possible letter combinations corresponding to that prefix, namely
{"MJA", "MJB", "MJC", "MKA", "MKB", "MKC", "MLA", "MLB", "MLC",
"NJA", "NJB", "NJC", "NKA", "NKB", "NKC", "NLA", "NLB", "NLC", "OJA",
"OJB", "OJC", "OKA", "OKB", "OKC", "OLA", "OLB", "OLC"}
Note that if the argument passed to phoneSpell
contains a 0 or 1, that position in the output should
simply be displayed as that digit, since there are no letters that correspond to it.
I've tried various things like first converting the number to a String
using ToString
and getting the Length
using StringLength
. I've tried a combination of Outer
and Tuples
to get the different combinations, but I'm not getting much luck. Any pointers in the right direction will be appreciated. Thanks.