I am coding a part of a big application where I am facing this problem. I will abstract you all from all the details by presenting a similar plain-vanilla scenario.
I am given n (the no. of digits of the number to be formed at run-time).
I am also given a list of numbers say {2,4,8,9}.
I have to form all the possible numbers that can be formed from the above list of the given length.
e.g. if n = 3 and list = {4, 5, 6}
then the possible number are:
444,
445,
446,
454,
455,
456,
464,
465,
466,
and so on...
Any help will be appreciated!
regards
shahensha
Use recursive function. This is an example in javascript...
my approach would be the following:
and then for the n-digit problem:
this should do the magic. The code should be self-explanatory, if it isn't please leave a comment.
You'll have to pay attention if the list items can be longer than a digit. Then you need to add the following in the combine function:
and of course give n to the combine function.
In the end in nDigit you have to check if there are combinations with length less than n
I wrote following F# code to solve this problem:
So,
Will print
all 27 values
Your task is equivalent to count in a base different from 10, as the following C++ program demonstrates:
The obvious problem with this approach is given by the easy overflow of
max
for high enough values ofn
andm
. You can solve that by mimicking the counting using an array ofm
linked lists, which must represent the "digits".You can use recursion. Say the numbers you can use are in an array.
C# code:
And then call: