I want to print all number combinations that are in ascending order. The output should go like: 012, 013, 014, ..., 789 for n = 3. I tried to solve it using recursion, however I'm having the StackOverflowError. So it means it never reaches the result. Here is my code so far:
public class Main {
public static void main(String[] args) {
int[] a = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
print_combinations(a, 0, 3);
}
static void print_combinations(int[] a, int index, int n) {
if (n > 0 && n < 10) {
if (index == n - 1) {
if (is_ascending(a, n)) {
System.out.print(Arrays.toString(a));
System.out.print(", ");
}
if (!has_ended(a, n)) {
print_combinations(a, 0, n);
}
} else {
while (a[index] <= 9 - n + index - 1) {
print_combinations(a, index + 1, n);
if (index < n - 1 && a[index] == 9 - n + index - 1) {
a[index + 1] = 0;
}
a[index]++;
}
}
}
}
static boolean has_ended(int[] a, int n) {
int ctr = 0;
while (ctr < n) {
if (a[ctr] != 10 - n + ctr) {
return false;
} else {
ctr++;
}
}
return true;
}
static boolean is_ascending(int[] a, int n) {
int ctr = 0;
while (ctr < n - 1) {
if (a[ctr] >= a[ctr + 1]) {
return false;
}
ctr++;
}
return true;
}
}```