-
Notifications
You must be signed in to change notification settings - Fork 0
/
csp_solver_nl.ex
56 lines (45 loc) · 1.25 KB
/
csp_solver_nl.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
defmodule Csp.NormalList.Solver do
@compile {:inline, is_solution?: 2, generate: 3, solve: 3}
@entropy 10
@max_digit @entropy
@rng @entropy..1
def init() do
# IO.puts("q INIT CHILDREN")
# in the form [1], [2], ..
Enum.map(@rng, &[&1])
end
def generate(q, parent_items, stat) do
case length(parent_items) >= @max_digit do
true ->
{q, stat}
false ->
# IO.puts("GEN CHILDREN for #{inspect(parent_items)}")
children = for c <- @rng, do: [c | parent_items]
# add children to stack
{children ++ q, stat + @entropy}
end
end
def solve(q, solution, stat) do
# IO.puts("QUEUE: #{inspect(q)}")
item = hd(q)
# check if it is a solution?
case is_solution?(item, solution) do
true ->
IO.puts("FOUND A SOLUTION #{inspect(item, charlists: :as_list)}, count: #{stat}")
:ok
false ->
# if not, generate children from this item
{q, stat} = generate(tl(q), item, stat)
case q == [] do
true ->
IO.puts("q IS EMPTY!, QUITTING!, count: #{stat}")
:exit
false ->
solve(q, solution, stat)
end
end
end
defp is_solution?(item, solution) do
item == solution
end
end