letter digit phone problem
Example
Use this image as a reference:
Courtesy of wikipedia
As you can see, from our example up above 2 maps to [a, b, c]
and 3 maps to [d, e, f]
.
To calculate the possibilities you multiply the length of each array you’d have against each other. We have 2
arrays with length 3
so:
3 * 3 = 9
Okay, we got the possiblities. How do we actually solve this? Well, let’s just start with solving that one single case.
Get the maps together⌗
We need to first get the arrays together in a two dimensional array, this is easy to do. Convert the number to string, and run each through digit.
Generate the combinations⌗
Aight, cool we got our arrays in a two-dimensional array. What’s next? Oh yeah, we wanna generate the possible patterns for our particular case(array with length 2).
This is cool, but this only applies to one possible case. Which is two digit numbers, like 23
or 45
. But not to digits bigger than two or less than two :(.
What do we do then? We’ll we can’t add more loops, cause that wouldn’t be dynamic. If we had 5 digits, we’d have 5 loops and that gets more complex the bigger the digits are.
Thankfully there is a better way to do this.
Modify the array in-place⌗
This means, the second item in the array should have the combination of the first item and the second item.
For example, say we want to calculate the combinations of 234
. Our function should work like this:
So we combine two arrays together, and the second item becomes that combination. The whole process is idiomatic.
A javascript implementation would like this:
and Voilà, the solution is dynamic.
I came by this problem originally from https://dailycodingproblem.com - They send you daily interview problems, so you could improve your algorithm skills…
If you a want a full-solution implemented in golang, checkout my github repo algo.