# Esercizio Sudoku
# Dichiarazioni DATA
set N:= {1..9}; # cifre
set R:= {1..9}; # righe
set C:= {1..9}; # colonne 
set T:= {1..3}; # terne
param s {R, C}; # valori fissati inizialmente

# VARIABILI 

# Variabili di assegnamento
var x {R, C, N} binary;

# VINCOLI 
subject to Cifre {r in R, c in C}:
  sum {n in N} x[r,c,n] = 1;

subject to Righe {r in R, n in N}:
  sum {c in C} x[r,c,n] = 1;

subject to Colonne {c in C, n in N}:
  sum {r in R} x[r,c,n] = 1;

subject to Terne {T_R in T, T_C in T, n in N}:
  sum {r in R, c in C: (r>=3*T_R-2) and (r<=3*T_R) and (c>=3*T_C-2) and (c<=3*T_C)} x[r,c,n] = 1;
  
subject to Valori_fissati {r in R, c in C: s[r,c] > 0}:
  x[r,c,s[r,c]] = 1;

###############
solve;
###############

printf ' *** Soluzione del sudoku ***\n\n' > "Sudoku.sol";
for {r in R}
  {for {c in C}
     printf '%3d', sum {n in N} n*x[r,c,n] >> "Sudoku.sol";
   printf '\n' >> "Sudoku.sol";
  }

###############
data;
###############

param s:	1	2	3	4	5	6	7	8	9 :=
1			1	0 	0 	2	0 	0 	0 	0 	0 
2			0 	2	0 	0 	3	0 	0 	0 	0 
3			0 	0 	4	0 	0 	1	0 	0 	0 
4			0 	0 	3	0 	0 	5	0 	0 	6
5			0 	7	0 	0 	0 	0 	0 	4	0 
6			8	0 	0 	9	0 	0 	2	0 	0 
7			9	0 	0 	8	0 	0 	7	0 	0 
8			0 	3	0 	0	9	0 	0 	1	0 
9			0 	0 	2	0 	0 	6	0 	0 	5;

end;
