随便发一个sudoku的gams代码。最主要的是请大家理解set 里面mapping 的写法。% \$ X2 i: u" {# r
Sets r rows / r1*r9 /# T3 [5 C5 n5 L* f6 g! b
c columns / c1*c9 /) x- G. Y* B0 |% D8 @& [ Z/ T
b blocks / b1*b9 / / x& B1 n% P2 n v values / v1*v9 /( n* f1 B8 k/ H
br(b,r) / b1*b3 .r1*r3, b4*b6 .r4*r6, b7*b9 .r7*r9 /0 h2 H2 |* k8 K$ [ U! P
bc(b,c) / (b1,b4,b7).c1*c3, (b2,b5,b8).c4*c6, (b3,b6,b9).c7*c9 /& ?9 |* A2 k F) u+ k
brc(b,r,c) block definitions ;2 D( g5 }: `$ S+ G) u) @; C- v
+ A8 a; g5 m8 {8 Y3 A# M5 \' {
brc(b,r,c) = br(b,r)*bc(b,c); 1 w; `* Q% l% i, e- r * T4 K8 m: O* i9 X. JTable problem(r,c) Hard problem with non-unique solution 8 U& D' g9 P! m c1 c2 c3 c4 c5 c6 c7 c8 c9% w1 o( O7 Q8 J$ [
r1 2 6 7 8 }8 {; s/ u1 x# nr2 6 2/ ?% ~, u3 W' M* e
r3 4 8 1 # _ _6 m* f# k8 Y" sr4 5 9 3" h& `& Q' b; f0 q
r5 3 51 ~3 M6 r( P, a& D/ S, r
r6 2 8 7/ h- R% {9 d+ L
r7 17 s$ P3 c% x, h% G! C9 o
r8 7 8 6 [9 Q- k+ u$ P1 o) e9 M7 v- _. M
r9 5 3 8 ;) r6 ~4 M, n. R6 P m3 m5 w7 v7 g& U
+ n) M( k$ q3 j4 H . m0 |0 `7 e' F4 H: M! `$ `5 bBinary Variable X(r,c,v) assign value to cell (defined by row and column);! x4 R3 q: ]& I* s Q* I
Variable W objectiv value - anything; h" J! @$ V! B* I1 N0 U F
+ J2 ~+ Q, b. e9 x( I% G' o2 n6 K
equations eq1(r,c) exactly one value for each cell$ z( a' w0 y/ P8 [, W' i
eq2(c,v) column entries have to be unique A' ?" c1 r! t9 g5 v: I eq3(r,v) row entries have to be unique/ _" s+ u, S: K& v% P
eq4(b,v) block entries have to be unique: I {2 |- K2 c9 v6 A$ {: m$ @0 o
nobj definition of objective - anything; ( z6 Y+ @; d/ P$ N% S, b7 Q" @' o6 m3 Z: H
X.fx(r,c,v)$(problem(r,c)=ord(v)) = 1;2 V1 [% I% y& z' e; u
9 w2 s( Q- H' c3 ^( \
eq1(r,c).. sum(v, X(r,c,v)) =E= 1; ' k, g q X& C0 V$ I6 a6 Meq2(c,v).. sum(r, X(r,c,v)) =E= 1;6 l5 h) B# t7 A, B. c# p5 n, B
eq3(r,v).. sum(c, X(r,c,v)) =E= 1; * i8 W( z1 E+ I, ]4 N0 b% ]eq4(b,v).. sum(brc(b,r,c), X(r,c,v)) =E= 1;8 A- W- ]0 W: r+ P$ {8 m9 F
nobj.. W =E= sum((r,c,v), X(r,c,v));9 v1 L* J t7 {9 K* ]! f
( z0 ?* g2 m3 emodel sudoku / all /; % y' z: q" o2 Y! q4 c 5 n; N" e: M8 ~solve sudoku minimizing w using mip; ! E' ~$ q8 k3 @/ N2 v: D最后说一句,其实这个模型不用求什么最大还是最小值,只要得到一个满足所有constraints的feasible solution 就可以了,所以nobj的注释写的"anything"。