Skip to content

Instantly share code, notes, and snippets.

@MachinesAreUs
Last active September 13, 2017 12:59
Show Gist options
  • Save MachinesAreUs/4e635d6c5deea4b2455a51732eb31fff to your computer and use it in GitHub Desktop.
Save MachinesAreUs/4e635d6c5deea4b2455a51732eb31fff to your computer and use it in GitHub Desktop.
n-queens in elixir
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