-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolve-2.exs
More file actions
53 lines (40 loc) · 1.06 KB
/
Copy pathsolve-2.exs
File metadata and controls
53 lines (40 loc) · 1.06 KB
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
defmodule Solve do
use Agent
def start do
Agent.start_link(fn -> %{0 => 0, 1 => 1} end, name: __MODULE__)
end
def factorial(n) when n == 0, do: 0
def factorial(n) do
cached_value = memo(n)
if cached_value do
cached_value
else
value = n + factorial(n - 1)
memo(n, value)
value
end
end
def memo(n) do
Agent.get(__MODULE__, &(Map.get(&1, n)))
end
def memo(n, value) do
Agent.update(__MODULE__, &(Map.put(&1, n, value)))
end
end
{[input: raw_input], _, _} = OptionParser.parse(System.argv(), strict: [input: :string])
Solve.start()
positions = File.stream!(raw_input)
|> Stream.map(&String.trim/1)
|> Stream.flat_map(&(String.split(&1, ",")))
|> Stream.map(&String.to_integer/1)
|> Enum.sort()
min = List.first(positions)
max = List.last(positions)
options = min..max |> Enum.map(fn position ->
{position, positions |> Enum.map(&(Solve.factorial(abs(&1 - position)))) |> Enum.sum()}
end)
IO.inspect(options)
IO.inspect(options |> Enum.min_by(fn option ->
{_position, fuel} = option
fuel
end))