Reputation: 1
I am trying to code "Peaceable armies of queens" problem. The goal is to put possible maximum equal no. of black and white queens on the chessboard so that they dont attack each other but they can attack within same color.
I have implemented and tried the following code on SICStus 4.3.2. The problem with this code is that it executes faster until the chess board size 8 but then it takes much time for N>8. Here N is the Maximum equal no. of queens (black and white) S is the matrix for showing positions of black and white queens on the chessboard. 7 is the size of chessboard.
so the query is,
| ?- queens(S,7,N).
S = [[0,-1,-1,-1,0,0,0],[0,0,0,0,0,1,1],[-1,0,0,-1,0,0,0],[-1,-1,0,0,0,0,0],[0,0,0,0,1,0|...],[0,0,0,0,1|...],[0,0,0,0|...]],
N = 7 ?
yes
but it takes much time for
| ?- queens(S,10,N).
so the question is how to optimize this code so that it executes faster?
-1 -> Black Queen
0 -> Free place
1 -> White Queen
Mat -> matrix for showing positions of black and white queens on chessboard Dim -> Dimimension or Size of chessboard N -> Maximum possible equal number of queens from black and white army of queens placed on chessboard
:-use_module(library(clpfd)),use_module(library(lists)).
queens(Mat,Dim,N):-
Dim > 2,
Ls is Dim*Dim,
length(Sol, Ls),
N #> 0, N #< Ls/4,
domain(Sol, -1,1),
list_to_matrix(Sol, Dim, Mat),
row(Mat, 1, Row1),
domain(Row1, -1, 0),
column(Mat, 1, Col1),
domain(Col1, -1, 0),
row(Mat, Dim, RowDim),
domain(RowDim, 0, 1),
column(Mat, Dim, ColDim),
domain(ColDim, 0, 1),
diag(Mat, Dimiag, 0, Dim),
domain(Dimiag, 0, 1),
nth1(Dim, RowDim, LRow),
LRow is 1,
global_cardinality(Sol, [-1-N, 1-N, 0-_]),
check_rows(Mat),
transpose(Mat, B),
check_rows(B),
diag_to_list(Mat, X1, Dim),
check_rows(X1),
matrix_reverse(Mat, C),
diag_to_list(C, X2, Dim),
check_rows(X2),
labeling([maximize(N), ffc],Sol).
Upvotes: 0
Views: 97