Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better Eight Queens program #113

Open
lambdacalculator opened this issue Oct 25, 2019 · 0 comments
Open

Better Eight Queens program #113

lambdacalculator opened this issue Oct 25, 2019 · 0 comments

Comments

@lambdacalculator
Copy link

The Eight Queens program included in Examples (citation: O'Keefe, The Craft of Prolog) is unnecessarily complicated and wasteful in its data structure. Here is a much simpler program that uses the same idea (diagonals as lists of logic variables shared with columns), adapted from a program in Chapter 9 of van Roy and Haridi, Concepts, Techniques, and Models of Computer Programming, 2004:

queens(N, Queens) :-
    length(Queens, N),
    place_queens(N, Queens, _, _).

place_queens(0, _, _, _) :- !.
place_queens(N, Cs, Us, [_|Ds]) :-
    M is N - 1,
    place_queens(M, Cs, [_|Us], Ds),
    place_queen(N, Cs, Us, Ds).

place_queen(N, [N|_], [N|_], [N|_]).
place_queen(N, [_|Cs], [_|Us], [_|Ds]) :-
    place_queen(N, Cs, Us, Ds).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant