-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnqueens.ex
95 lines (78 loc) · 1.98 KB
/
nqueens.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
defmodule NQueens do
@moduledoc false
# Example: N-queens solver.
require Logger
import MinizincUtils
@nqueens_model resource_file("mzn/nqueens.mzn")
@queen_symbol "\u2655"
# N queens puzzle
# Async solving
def solve(n, opts \\ [solution_handler: &solution_handler/2]) do
MinizincSolver.solve(@nqueens_model, %{n: n}, opts)
end
def solve_sync(n, opts \\ [solution_handler: NQueens.Handler]) do
MinizincSolver.solve_sync(@nqueens_model, %{n: n}, opts)
end
@doc false
## Printing solver stats
def solution_handler(
:summary,
%{solver_stats: stats, status: status} = summary
)
do
Logger.info "Solution status: #{status}"
Logger.info "Solver stats:\n #{inspect stats}"
summary
end
## Printing solutions
def solution_handler(
:solution,
%{
index: _count,
data: data
} = solution
) do
Logger.info print_board(data["q"]) <> "\n-----------------------"
solution
end
def solution_handler(event, data) do
MinizincHandler.handle_solver_event(event, data, MinizincHandler.Default)
end
@doc false
## queens[i] = j <=> row i has a queen in position j.
def print_board(queens) do
n = length(queens)
"\n" <> Enum.join(
for i <- 1..n do
Enum.join(
for j <- 1..n do
if Enum.at(queens, i - 1) == j, do: @queen_symbol, else: "."
end,
" "
)
end,
"\n"
)
end
end
defmodule NQueens.Handler do
@moduledoc false
require Logger
import NQueens
use MinizincHandler
@doc false
def handle_solution(%{data: data} = solution) do
Logger.info print_board(data["q"]) <> "\n-----------------------"
solution
end
@doc false
def handle_summary(%{solver_stats: solver_stats} = summary) do
Logger.info "Solver stats:\n #{inspect solver_stats}"
summary
end
@doc false
def handle_minizinc_error(error) do
Logger.info "Minizinc error: #{error}"
error
end
end