Sie sind auf Seite 1von 13

G53CLP

Constraint Logic Programming

Dr Rong Qu
Modeling CSPs – Case Study II
Solving Sudoku
 Variables 6 5 2
 posi,j: number placed 3 9
at position (i,j) 7 6 1
6 3 4
4 7 1
 Domain
5 9 8
 posi,j = {1, …, 9}
4 1 6
3 8
2 4 5

G53CLP – Constraint Logic Programming Dr R. Qu 2


Solving Sudoku
 Constraints 6 5 2
 {1, …, 9} on each row 3 9
 {1, …, 9} on each 7 6 1
column 6 3 4
 {1, …, 9} in each 3X3 4 7 1
square 5 9 8
4 1 6
3 8
2 4 5

G53CLP – Constraint Logic Programming Dr R. Qu 3


Solving Sudoku
 Constraints 6 5 2
1. All different each 3 9
row 7 6 1
2. All different each 6 3 4
column 4 7 1
3. All different each 5 9 8
3X3 square 4 1 6
3 8
 How to model 2 4 5
constraint 3?

G53CLP – Constraint Logic Programming Dr R. Qu 4


Solving Sudoku
 Constraints 6 5 2
 All different pos[i,j] = 3 9
{1, …, 9} 7 6 1
 i = {1, 2, 3}; {4, 5, 6} 6 3 4
or {7, 8, 9} 4 7 1
 j = {1, 2, 3}; {4, 5, 6} 5 9 8
or {7, 8, 9} 4 1 6
3 8
2 4 5

G53CLP – Constraint Logic Programming Dr R. Qu 5


Solving Sudoku – Demo
Data File & Project in OPL
 Input data in OPL

 Project in OPL
 Add/insert model file .mod
 Add/insert data file .dat
 Data type declared in model file .mod will look up
the data file .dat

G53CLP – Constraint Logic Programming Dr R. Qu 7


6 5 2
3 9
7 6 1
6 3 4

Solving Sudoku in OPL 4


5
7
9
1
8
4 1 6
//.dat file 3 8

input= 2 4 5

[[0 6 0 0 5 0 0 2 0]
[0 0 0 3 0 0 0 9 0]
[7 0 0 6 0 0 0 1 0]
[0 0 6 0 3 0 4 0 0]
[0 0 4 0 7 0 1 0 0]
[0 0 5 0 9 0 8 0 0]
[0 4 0 0 0 1 0 0 6]
[0 3 0 0 0 8 0 0 0]
[0 2 0 0 4 0 0 5 0]];

G53CLP – Constraint Logic Programming Dr R. Qu 8


6 5 2
3 9
7 6 1
6 3 4

Solving Sudoku in OPL 4


5
7
9
1
8
4 1 6
//.mod file 3 8

range dim1 1..9; 2 4 5

range dim2 1..9;


range bindex 0..2;
int input[dim1,dim2] = ...; //read in the .dat

{int} setnum[f in bindex] = {x | x in dim1: x < (4+3*f)


& x > 3*f };

var int pos[dim1,dim2] in 1..9;

G53CLP – Constraint Logic Programming Dr R. Qu 9


Solving Sudoku in OPL
solve{
forall(i in 1..9)
forall(j in dim2 : input[i,j] <> 0)
pos[i,j] = input[i,j] ;

};
G53CLP – Constraint Logic Programming Dr R. Qu 10
Solving Sudoku in OPL
solve{

forall(j in dim2)
alldifferent(all(i in dim1) pos[i,j]);

forall(i in dim1)
alldifferent(all(j in dim2) pos[i,j]);

};
G53CLP – Constraint Logic Programming Dr R. Qu 11
Solving Sudoku in OPL
solve{

forall(b1 in bindex){
forall(b2 in bindex){
alldifferent(all(i in setnum[b1], j in
setnum[b2]) pos[i,j]);

}
}
};
G53CLP – Constraint Logic Programming Dr R. Qu 12
Exercise – Coins in Bank
 You have a bag of coins to save in your bank
 Weights of coins
£1 50p 20p 10p 5p 2p 1p
Weight(g) 10 8 6 5 3 2 1

 If the bag of coins weighs 131g, how much in


total?
 How about 4g? How many possible solutions?
 How can you solve this problem?
Lab session next week

G53CLP – Constraint Logic Programming Dr R. Qu 13

Das könnte Ihnen auch gefallen