The problem goes like this:
There is a lock of 4-digit PIN. The digits have to be chosen from the digits 0-5
for the key to unlock.
We need to Find all possible combination like 0001, 0002, 0003, 0004
, and so on.
The problem goes like this:
There is a lock of 4-digit PIN. The digits have to be chosen from the digits 0-5
for the key to unlock.
We need to Find all possible combination like 0001, 0002, 0003, 0004
, and so on.
3
Answers
Here's how to approach the problem recursively.
We need to divide the problems into sub problems and find the solution to smallest subproblem we could solve.
That gives our base case, i.e, for
0
digit pin we'll have""
Now lets break the problem into sub problems and attempt to solve that. We try the first digit of the pin with
0
, then we only have to solve the problem for the remaining three digits. Same goes if the first digit we try with1
and so on.So let's proceed with this
You can create an array for the digits and increment the earlier digits until you find one that was not 9, just like you increment numbers in general:
Here is my approach, I’ve probably made this more complicated than it has to be. I’ve concentrated more on using recursion properly (no global variables and the function returns the final result or a call to itself).
The
for
loop in there is required (or, at least, another recursive function) if thedigitsCount
can be variable.The main driver of this approach is using modulus (
%
) and theflag
variable to make the countingrange
based (in this case, 5 based).