Please help me to find out how to write method that prints all possible combination of numbers from 1 to N. I can't use arrays, collections or strings. I need output like that (for 3):
[1] [2] [3]
[1] [3] [2]
[2] [1] [3]
[2] [3] [1]
[3] [2] [1]
[3] [1] [2]
There is no problem to write such method using array:
public class Test {
static void permute(int[] a, int k) {
if (k == a.length) {
for (int i = 0; i < a.length; i++) {
System.out.print(" [" + a[i] + "] ");
}
System.out.println();
} else {
for (int i = k; i < a.length; i++) {
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
public static void main(String args[]) {
int N = 3;
int[] sequence = new int[N];
for (int i = 0; i < N; i++) {
sequence[i] = i + 1;
}
permute(sequence, 0);
}
}
Thanks in advance for any help!
UPD 1. I'm also trying to write something like this (but unsuccessful):
public class Combinations {
private static int change;
public void doIt(int n, int pos) {
if (pos == n) {
for (int f = 1; f <= n; f++) {
System.out.print(f + " ");
}
System.out.println("");
} else {
for (int i = pos; i < n; i++) {
change = pos;
System.out.print(change + " ");
pos = i;
System.out.print(pos + " ");
i = change;
System.out.print(i + " ");
System.out.println("");
doIt(n, pos + 1);
change = pos;
System.out.print(change + " ");
pos = i;
System.out.print(pos + " ");
i = change;
System.out.print(i + " ");
System.out.println("");
}
}
}
}
printinside your method, without newline except where appropriate.