Browse Source

Solve 2021 Day 7 part 2 in elixir

master
Garrit Franke 2 years ago
parent
commit
83f3ae45af
Signed by: garrit
GPG Key ID: 65586C4DDA55EA2C
  1. 39
      2021/Day7/Elixir/whales.ex

39
2021/Day7/Elixir/whales.ex

@ -10,6 +10,12 @@ defmodule Whales do
def distance_to(a, b), do: abs(a - b)
def increasing_distance_to(a, b) do
1..abs(a - b)
|> Enum.to_list()
|> Enum.sum()
end
def find_cheapest_route(positions),
do: find_cheapest_route(positions, Enum.min(positions), nil)
@ -37,6 +43,37 @@ defmodule Whales do
end
end
def find_new_cheapest_route(positions),
do: find_new_cheapest_route(positions, Enum.min(positions), nil)
def find_new_cheapest_route(positions, target, cheapest) do
# This takes a while, so we add debug output
IO.inspect(target, label: "Target")
IO.inspect(Enum.count(positions), label: "Positions")
if target >= Enum.count(positions) + 1 do
cheapest
else
current =
if target == Enum.max(positions) + 1 do
cheapest
else
positions
|> Enum.map(fn position -> increasing_distance_to(position, target) end)
|> Enum.sum()
end
new_cheapest =
if current < cheapest do
current
else
cheapest
end
find_new_cheapest_route(positions, target + 1, new_cheapest)
end
end
@spec first() :: Integer
def first() do
positions = load_file("../input.txt")
@ -45,6 +82,8 @@ defmodule Whales do
@spec second() :: Integer
def second() do
positions = load_file("../input.txt")
find_new_cheapest_route(positions)
end
end

Loading…
Cancel
Save