How do I fix the following error in my prolog code for the queen problem

47 Views Asked by At

I can't figure out why my code isn't working. I want the code to give me possible combinations for N queens on a NxN chessboard. A possible combination would be e.g. [2, 4, 1, 3] for a 4x4 chessboard. Each digit represent the colume the queen is being placed and as we go through the list we go row by row until we reach the last one. So "2" would be place in the first row in colume 2, "4" would be placed in the second row in colume 4 and so on.

When I use the function n_queens it gives me

the follwing error:

ERROR: Arguments are not sufficiently instantiated

The code:

initliste(M,N,[M|Ns]) :- M < N, M1 is M+1, initliste(M1,N,Ns).
initliste(N,N,[N]).


safe([]).
safe([Q|Qs]) :-
    \+attack(Q, Qs),
    safe(Qs).

attack(X, [Y|Ys]) :-
    X =\= Y,
    abs(X-Y) =\= L,
    L is length([Y|Ys]),
    attack(X, Ys).
attack(_, []).

n_queens(N, L) :-
    initliste(1,N,Board),
    permutation(Board, L),
    safe(L).
1

There are 1 best solutions below

2
Scott Hunter On

You try to compare L (in abs(X-Y) =\= L) before binding a value to L (as you do in L is length([Y|Ys])).