I was faced with a question recently in C. We have a phone's numpad with following layout:
1[abc] 2[def] 3[ghi] 4[jkl] 5[mno] 6[pqr] 7[st] 8[uv] 9[wx] 0[yz]
How to come up with an API which gives all possible combinations of characters belonging to each number for a given numeral input.
For e.g. input = 1234
Then the API should print all possible combinations of characters-
adgj
bdgj
cdgj
aegj
begj
cegj
.. and so on.
Is there a simple way to do it? Apart from hardcoded nested for
loops.
I was given a hint as recursion but couldn't figure a way out of it.
Recursion is just a sneaky way of nesting four
for
loops. Here's what the code looks likeYou can also solve this problem, and similar combinatorial problems, with a simple counting algorithm. A counting algorithm emulates natural counting, in which you increment the least significant digit from 0 to 9. When the least significant digit wraps from 9 back to 0, the next digit to the left is incremented.
The same can be done to solve the OP's problem. But in this case, the digits have either two or three possible values. And if you examine the pattern in the OP, it's readily apparent that the least significant digit is on the left. In the pattern
adgj
bdgj
cdgj
aegj
you can see that
a
becomesb
,b
becomesc
, and whenc
wraps back toa
, thend
becomese
.Here's the code