An algorithm for generating all possible N-digit numbers whose numbers are in ascending order

I want the algorithm to generate all possible N-digit numbers whose numbers are in ascending order.

for example: if N = 3, then the possible numbers are: 012,123,234,246,567,259, because:

0 <1 & Lt; 2

...

2 <5 & Lt; nine

and etc.

How can i do this?

I developed the following algorithm, but it only generates numbers with consecutive increasing digits, such as 123,234,345,456,567, etc. Consequently, a large set of numbers is missing.

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); } } 
+6
source share
2 answers

Trying to keep the 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); } } 
+5
source

From a more declarative angle, the algorithm will look almost like mathematical notation (in Haskell):

 generate = toInt [[a,b,c] | a <- x, b <- x, c <- x, a < b, b < c] where x = [0..9] toInt = map (foldl (\nm -> 10*n + m) 0) 

where map (foldl (\nm -> 10*n + m) 0) simply translates the list of digits into an integer and the rest is a kind of self-documentation: take three digits, subject to this restriction.

0
source

Source: https://habr.com/ru/post/956547/


All Articles