Last active
September 13, 2017 12:59
-
-
Save MachinesAreUs/4e635d6c5deea4b2455a51732eb31fff to your computer and use it in GitHub Desktop.
n-queens in elixir
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
defmodule Queens do | |
def solve(0, _m), do: [[]] | |
def solve(n, m) do | |
for done_queens <- solve(n-1, m), | |
avail_pos <- (Enum.to_list(1..m) -- done_queens), | |
safe_pos(avail_pos, done_queens, 1), | |
do: [avail_pos | done_queens] | |
end | |
defp safe_pos(_, [], _), do: true | |
defp safe_pos(pos, [queen | queens], distance) do | |
(pos != queen + distance) and | |
(pos != queen - distance) and | |
safe_pos(pos, queens, distance+1) | |
end | |
end | |
:io.write Queens.solve(8,8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment