Created
June 29, 2013 08:16
-
-
Save pazworld/5890333 to your computer and use it in GitHub Desktop.
「エイト・クイーン問題」をErlangで その2 ref: http://qiita.com/pazworld/items/b3316f32fc14d1774087
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% solve 8-queens problem. | |
-module(eq2). | |
-export([solve/0, solve_count/0, solve_display/0]). | |
% Solve and return answer as a list of lists. | |
solve() -> solve(1, [], []). | |
% Solve and return count of answers. | |
solve_count() -> length(solve()). | |
% Solve and display them in user friendly style. | |
solve_display() -> lists:foreach(fun display/1, solve()). | |
% Found an answer of queens position. | |
solve(_, Queens, L) when length(Queens) == 8 -> | |
solve(hd(Queens) + 1, tl(Queens), [Queens|L]); | |
% Finished searching all cell on the board. | |
solve(9, [], L) -> L; | |
% Finished searching one line. | |
solve(9, [H|T], L) -> solve(H + 1, T, L); | |
% Search. | |
solve(Col, Queens, L) -> | |
case not conflict(Col, Queens) of | |
true -> solve(1, [Col | Queens], L); | |
false -> solve(Col + 1, Queens, L) | |
end. | |
% Check if a column conflicts with queens. | |
conflict(Col, Queens) -> | |
Conflict = fun({N, QCol}) -> Col == QCol orelse abs(Col - QCol) == N end, | |
lists:any(Conflict, with_idx(Queens)). | |
% [a,b,c] -> [{1,a},{2,b},{3,c}]. | |
with_idx(L) -> lists:zip(lists:seq(1, length(L)), L). | |
% Display board. | |
display(Queens) -> | |
Frame = "**********", | |
io:fwrite("~s~n", [Frame]), | |
lists:foreach(fun(X) -> io:fwrite("*~s*~n", [make_line(X)]) end, Queens), | |
io:fwrite("~s~n~n", [Frame]). | |
% Make a line of board. | |
make_line(X) -> string:chars($., X - 1) ++ "Q" ++ string:chars($., 8 - X). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment