I want an algorithm to generate all possible N-digit numbers, whose digits are in increasing order.
e.g.: if N=3, then possible numbers are: 012,123,234,246,567,259, because:
0<1<2
...
2<5<9
etc.
How can I do it?
I developed the following algorithm but it only generates the numbers with consecutive increasing digits like 123,234,345,456,567, etc.. Hence, a large set of numbers is missed out.
private static void generate(int start,int n)
{
if((start+n)>9)
return;
else
{
for(int i=0;i<n;i++)
System.out.print(start+i);
System.out.println();
generate(start+1,n);
}
}
A number is strictly increasing if every digit is greater than its preceding digit. A simple solution would be to generate all n–digit numbers and print only those numbers that satisfy the given constraints.
Find N digits number which is divisible by D in C++ If N is 3, and D is 5, then the number can be 500. This can be solved easily. If D is 10 and N is 1, then it will be impossible. We can put D, and suppose the D has m number of digits, then attach N – m number of 0s to make it N digit number and divisible by D.
Trying to preserve your original idea:
private static void generate(int prefix, int start, int n)
{
if (n == 0)
{
System.out.print(prefix);
System.out.println();
}
else
{
for(int i=start;i<10;i++)
generate(10*prefix+i, i+1, n-1);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With