Reputation: 10480
I'm trying to make a pattern wherein N numbers 0-9 are displayed in every possible order.
class Main {
public static void perms(int[] arr, int i) {
if (i == arr.length) {
for (int j=0; j<arr.length; j++)
System.out.print(arr[j] + " ");
System.out.println();
return;
}
for (int j=i; j<arr.length; j++) {
for (int k=0; k<=9; k++) {
arr[j] = k;
perms(arr, j+1);
}
}
}
public static void main(String[] args) {
perms(new int[]{0,0}, 0);
}
}
This is the output I'm seeking for an array of length 2:
0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
1 0
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
2 0
2 1
2 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
3 0
3 1
3 2
3 3
3 4
3 5
3 6
3 7
3 8
3 9
4 0
4 1
4 2
4 3
4 4
4 5
4 6
4 7
4 8
4 9
5 0
5 1
5 2
5 3
5 4
5 5
5 6
5 7
5 8
5 9
6 0
6 1
6 2
6 3
6 4
6 5
6 6
6 7
6 8
6 9
7 0
7 1
7 2
7 3
7 4
7 5
7 6
7 7
7 8
7 9
8 0
8 1
8 2
8 3
8 4
8 5
8 6
8 7
8 8
8 9
9 0
9 1
9 2
9 3
9 4
9 5
9 6
9 7
9 8
9 9
It works but there is an extra output of:
9 0
9 1
9 2
9 3
9 4
9 5
9 6
9 7
9 8
9 9
at the very end when I run it. Why is this happening and how do I get rid of it?
Upvotes: 0
Views: 711
Reputation: 86
My recommendation for recursive function is you should always draw a diagram to simulate your coding process. For you program:
Then you can simply notice that, in level 1
when in loop k > 9
you have already printed all numbers you need, while the program does not stop, instead out loop j
will become to 1
and begin the next loop. This is the reason while you have extra {9, 0~9}
.
To understand why this happens, in this loop(refer to level 1), when j == 1
, variable arr = {9, 9}
(from the last loop operation when out loop j == 0
). That is to say the inner loop arr[j] = k
is modifying the second variable in the array which is arr[1]
. This operation is the same as level 2
.
One Possible solution:
public class Main {
public static void perms(int[] arr, int i) {
if (i == arr.length) {
for (int j=0; j<arr.length; j++)
System.out.print(arr[j] + " ");
System.out.println();
return;
}
for (int j=i; j<arr.length; j++) {
for (int k=0; k<=9; k++) {
arr[j] = k;
perms(arr, j+1);
}
// if arr = {9, 9}, break;
// this cannot put above the inner loop, I will
// leave that for you to think why
if(arr[0] == 9 && arr[1] == 9){
return;
}
}
}
public static void main(String[] args) {
perms(new int[]{0,0}, 0);
}
}
Or check this answer
Upvotes: 2