Finds magic squares (Wikipedia) of an arbitrary order n.
It first generates a list of every possible permutation of n integers that sum to the magic constant, which represents all possible rows, columns, and diagonals. For any one of those permutations, it attempts to construct a matrix whose first row is that permutation and whose first column is a another permutation that begins with the same entry and contains no other duplicate entries. Then, the algorithm attempts to find sum permutations to fill in the remaining rows and columns.
On my laptop with a 2.7GHz Intel Core i7 processor, the program finds all magic squares of order n in the following runtimes:
Order | Mean Runtime | Std. Dev. | Distinct Magic Squares |
---|---|---|---|
1 | .4ms | .9ms | 1 |
2 | .4ms | .5ms | 0 |
3 | 6.0ms | 1.7ms | 1 |
4 | 1.8seconds | .3seconds | 880 |
You can generate statistics of the program on your own machine with the generateRuntimeStats() test method.
It's probably not a great idea to try to run this for n >= 5. It'll work, it just might take a few years. That's my disclaimer.
Note: This program uses the Fork/Join framework and therefore requires Java SE 7 to compile and run.
Usage:
javac MagicSquares.java
java MagicSquares 3