Another update from ingydotnet^djgoku
This commit is contained in:
parent
91df62d461
commit
948b86eafa
7604 changed files with 108452 additions and 22726 deletions
36
Task/N-queens-problem/Elixir/n-queens-problem.elixir
Normal file
36
Task/N-queens-problem/Elixir/n-queens-problem.elixir
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
defmodule RC do
|
||||
def queen(n) do
|
||||
add = Tuple.duplicate(true, 2*n-1)
|
||||
sub = Tuple.duplicate(true, 2*n-1)
|
||||
solve(n, [], add, sub)
|
||||
end
|
||||
|
||||
def solve(n, row, _, _) when n <= length(row) do
|
||||
print(n,row)
|
||||
1
|
||||
end
|
||||
def solve(n, row, add, sub) do
|
||||
Enum.map(Enum.to_list(0..n-1) -- row, fn x ->
|
||||
iadd = x + (len = length(row))
|
||||
isub = if (y = x-len) < 0, do: y + 2*n - 1, else: y
|
||||
if elem(add, iadd) and elem(sub, isub) do
|
||||
solve(n, [x|row], put_elem(add,iadd,false), put_elem(sub,isub,false))
|
||||
else
|
||||
0
|
||||
end
|
||||
end) |> Enum.sum
|
||||
end
|
||||
|
||||
def print(n, row) do
|
||||
IO.puts frame = "+-" <> String.duplicate("--", n) <> "+"
|
||||
Enum.each(row, fn x ->
|
||||
line = Enum.map_join(0..n-1, fn i -> if x==i, do: "Q ", else: ". " end)
|
||||
IO.puts "| #{line}|"
|
||||
end)
|
||||
IO.puts frame
|
||||
end
|
||||
end
|
||||
|
||||
Enum.each(1..6, fn n ->
|
||||
IO.puts " #{n} Queen : #{RC.queen(n)}"
|
||||
end)
|
||||
Loading…
Add table
Add a link
Reference in a new issue