Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to generate all possible N-digit numbers with whose digits are in increasing order

Tags:

algorithm

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);
     }
}
like image 928
Naveen Avatar asked Oct 23 '13 10:10

Naveen


People also ask

What is a strictly increasing number?

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.

How do you find the N digit number in C++?

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.


1 Answers

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);
        }
    }
like image 193
Henrik Avatar answered Sep 28 '22 07:09

Henrik