00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040 package examples;
00041
00042 import static org.gecode.Gecode.*;
00043 import static org.gecode.GecodeEnumConstants.*;
00044
00045 import org.gecode.*;
00046
00047 public class MagicSquare extends Space {
00048 private int n;
00049 private VarMatrix<IntVar> m;
00050
00051 public MagicSquare(int size) {
00052 super("MagicSquare");
00053 n = size;
00054 final int
00055 nn = n*n,
00056 s = nn*(nn+1) / (2*n);
00057 m = new VarMatrix<IntVar>(this, n, n, IntVar.class, 1, nn);
00058
00059
00060 for (int i = n; i-- != 0; ) {
00061 linear(this, m.row(i), IRT_EQ, s);
00062 linear(this, m.col(i), IRT_EQ, s);
00063 }
00064
00065 {
00066 VarArray<IntVar> d1 = new VarArray<IntVar>(n);
00067 VarArray<IntVar> d2 = new VarArray<IntVar>(n);
00068 for (int i = 0; i<n; ++i) {
00069 d1.add(i, m.get(i,i));
00070 d2.add(i, m.get(n-i-1, i));
00071 }
00072 linear(this, d1, IRT_EQ, s);
00073 linear(this, d2, IRT_EQ, s);
00074 }
00075
00076
00077 distinct(this, m, ICL_DEF);
00078
00079
00080 rel(this, m.get(0,0), IRT_GR, m.get(0,n-1));
00081 rel(this, m.get(0,0), IRT_GR, m.get(n-1,0));
00082
00083 branch(this, m, INT_VAR_SIZE_MIN, INT_VAL_SPLIT_MIN);
00084 }
00085
00086 public MagicSquare(Boolean share, MagicSquare msq) {
00087 super(share, msq);
00088 n = msq.n;
00089 m = new VarMatrix<IntVar>(this, share, msq.m);
00090 }
00091
00092 public String toString() {
00093 String res = "";
00094 for (int i = 0; i < n; ++i) {
00095 for (int j = 0; j < n; ++j) {
00096 if (m.get(i,j).max() < 10) res += " ";
00097 res += m.get(i,j).toString();
00098 res += " ";
00099 }
00100 res += '\n';
00101 }
00102 return res;
00103 }
00104
00105 public void print() {
00106 System.out.println("Solution:");
00107
00108 System.out.println(toString());
00109 }
00110
00111 public static void main(String []args) {
00112 Options opt = new Options("MagicSquare");
00113 opt.size = 6;
00114 opt.gui = true;
00115 opt.parse(args);
00116
00117 MagicSquare ms = new MagicSquare(opt.size);
00118 opt.doSearch(ms);
00119 }
00120 }