import java.applet.*; import java.awt.*; public class FastChain9 extends Applet { int[] digit; int length = 9; public void init() { digit = new int[length]; PermutationGenerator permutationGenerator = new PermutationGenerator(length); int perms = permutationGenerator.factorial(length); digit = permutationGenerator.getThis(); if (!redundant() && isMagichain9()) print9(); for (int i = 1; i < perms; i++) { digit = permutationGenerator.getNext(); if (!redundant() && isMagichain9()) print9(); } } boolean redundant() { return (digit[0] < digit[1] || digit[0] < digit[8] || digit[8] < digit[7]); } boolean isMagichain9() // chain with same column and row sums { int total = digit[0] + digit[1] + digit[2]; if (total != digit[2] + digit[3] + digit[4]) return false; if (total != digit[4] + digit[5] + digit[6]) return false; if (total != digit[6] + digit[7] + digit[8]) return false; return true; } void print9() // prints sequence { String s = ""; for (int i=length-1; i>= 0; i--) s += String.valueOf(digit[i] + 1); System.out.println(s); } public void paint(Graphics g) { g.drawString("Results appear in the Java console", 20 , 25); } } // END OF Class FastChain9 class PermutationGenerator { int[] digit; int length; PermutationGenerator(int length) { this.length = length; digit = new int[length]; for (int i = 0; i < length; i++) digit[i] = i; } int[] getThis() { return(digit); } int[] getNext() { int i = length - 1; while (digit[i-1] > digit[i]) i--; int j = length; while (digit[j-1] <= digit[i-1]) j--; swap(i-1, j-1); i++; j = length; while (i < j) { swap(i-1, j-1); i++; j--; } return(digit); } void swap(int first, int second) { int temp = digit[first]; digit[first] = digit[second]; digit[second] = temp; } int factorial(int number) { int result = 1; for (int i = 1; i <= number; i++) result *= i; return result; } } // END OF Class PermutationGenerator