Turbo Prolog
Turbo Prolog
Turbo Prolog
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
string word ("" , [ 1 ) : -! .<br />
string:word(Str,[HIT1):bound(Str),frontstr(1,Str,H,S),string_word(S,T).string_word(Str,[HIT1):free(Str),bound(H),string_word(S,T),concat(H,T,Str).<br />
append( [1 ,L,L) :-!.<br />
append([XIL11,L2,[XIL31)<br />
repeat.<br />
repeat:-repeat.<br />
THE N QUEENS PROBLEM<br />
append(L1,L2,L3).<br />
In the N Queens problem, we try to place N queens on a chessboard in such a way that<br />
no two queens can take each other. Thus, no two queens can be placed on the same<br />
row, column or diagonal.<br />
To solve the problem, we'll number the rows and columns of the chessboard from I<br />
to N. To number the diagonals, we divide them into two types, so that a diagonal<br />
is uniquely specified by a type and a number calculated from its row and column<br />
numbers:<br />
Diagonal = N + Column - Row<br />
Diagonal = Row + Column - 1<br />
(type 1)<br />
(type 2)<br />
When the chessboard is viewed with row I at the top and column I on the left side,<br />
type I diagonals resemble the "\" character in shape and type 2 diagonals resemble the<br />
shape of"/". The numbering of type 2 diagonals on a 414 board is shown in Figure 10-4.<br />
I 2 3 4<br />
I I 2 3 4<br />
2 2 3 4 5<br />
3 3 4 5 6<br />
4 4 5 6 7<br />
Figure 10-4 The N Queens Chessboard<br />
To solve the N Queens problem with a <strong>Turbo</strong> <strong>Prolog</strong> program, we must record which<br />
rows, columns and diagonals are free and also make a note of where the queens are<br />
placed.<br />
A queen's position is described with a row number and a column number, as in the<br />
domain declaration<br />
Tutorial VIII: Spreading Your Wings 121