import java.util.Arrays;
public class Test {
public static void main(String[] args) {
System.out.printf("%3s %3s %3s %5s %3s%n",
"x1", "x2", "x3", "next", "y");
int a = 3;
int b = 4;
int x1, x2, x3, y = 0;
for(x1 = 1; x1 < b; x1++) {
for(x2 = 1; x2 < b; x2++) {
for(x3 = 1; x3 < b; x3++) {
int next = x1 * x2 * x3;
y += next;
System.out.printf("%2d %2d %2d %3d %4d%n",
x1, x2, x3, next, y);
}
}
}
System.out.printf("desired y = %d%n", y);
y = 0;
int[] counts = new int[a];
Arrays.fill(counts, 1);
int index = counts.length-1;
int lastCount = counts.length-1;
boolean more = true;
do {
int product = 1;
for(int i = 0; i < counts.length; i++) {
product *= counts[i];
}
y += product;
System.out.printf("index = %d counts = %s product = %2d y = %3d%n",
index, Arrays.toString(counts), product, y);
more = !isDone(counts, b-1);
if(counts[lastCount] == b-1) {
index = shiftUp(counts, index, b-1);
} else {
counts[lastCount]++;
}
} while(more);
System.out.printf("loop y = %d%n", y);
}
private static int shiftUp(int[] counters, int index, int max) {
int nextIndex = counters.length-1;
while(counters[nextIndex] == max && nextIndex > 0) {
counters[nextIndex] = 1;
nextIndex--;
}
for(int i = nextIndex+1; i < counters.length; i++) {
counters[i] = 1;
}
counters[nextIndex]++;
return nextIndex;
}
private static boolean isDone(int[] counters, int limit) {
for(int i = 0; i < counters.length; i++) {
if(counters[i] < limit)
return false;
}
return true;
}
}