Created
June 28, 2013 10:17
-
-
Save pazworld/5883760 to your computer and use it in GitHub Desktop.
「エイト・クイーン問題」をErlangで ref: http://qiita.com/pazworld/items/2a50f208ca2e5c1b4098
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(eq). | |
-compile(export_all). | |
solve() -> | |
register(counter, spawn(fun() -> counter(0) end)), | |
solve(cols(), []), | |
counter ! show. | |
cols() -> [1,2,3,4,5,6,7,8]. | |
solve(_, Queens) when length(Queens) == 8 -> display(Queens); | |
solve([], _) -> ok; | |
solve([Col|T], Queens) -> | |
case not conflict(Col, Queens) of | |
true -> solve(cols(), [Col | Queens]); | |
false -> ok | |
end, | |
solve(T, Queens). | |
conflict(Col, Queens) -> | |
Conflict = fun({N, QCol}) -> Col == QCol orelse abs(Col - QCol) == N end, | |
lists:any(Conflict, with_idx(Queens)). | |
with_idx(L) -> lists:zip(lists:seq(1, length(L)), L). | |
display(Queens) -> | |
counter ! countup, | |
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_line(X) -> string:chars($., X - 1) ++ "Q" ++ string:chars($., 8 - X). | |
counter(N) -> | |
receive | |
countup -> counter(N + 1); | |
show -> io:fwrite("Count: ~w~n", [N]) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment