refactor 2021 day 7
This commit is contained in:
parent
ec8ce0cd4e
commit
397d69c2ba
1 changed files with 22 additions and 20 deletions
|
@ -3,32 +3,34 @@ import AOC
|
||||||
aoc 2021, 7 do
|
aoc 2021, 7 do
|
||||||
use AOCHelpers
|
use AOCHelpers
|
||||||
|
|
||||||
def p1 do
|
def crabs(), do: input_number_list()
|
||||||
crabs = input_number_list()
|
|
||||||
|
|
||||||
max = Enum.max(crabs)
|
def p1, do: cost_of_most_efficient_position(&Function.identity/1)
|
||||||
|
|
||||||
for position <- 1..max do
|
def p2, do: cost_of_most_efficient_position(&(1 / 2 * &1 * (&1 + 1)))
|
||||||
for crab <- crabs do
|
|
||||||
abs(crab - position)
|
def total_fuel_cost_for_position(crab_freqs, pos, cost_fun) do
|
||||||
end
|
crab_freqs
|
||||||
|> Enum.sum()
|
|> Enum.reduce(0, fn {crab_pos, num_crab}, partial_cost ->
|
||||||
end
|
linear_distance = abs(crab_pos - pos)
|
||||||
|> Enum.min()
|
|
||||||
|
partial_cost + num_crab * cost_fun.(linear_distance)
|
||||||
|
end)
|
||||||
end
|
end
|
||||||
|
|
||||||
def p2 do
|
def cost_of_most_efficient_position(cost_fun) when is_function(cost_fun) do
|
||||||
crabs = input_number_list()
|
crab_positions = input_number_list()
|
||||||
|
|
||||||
max = Enum.max(crabs)
|
max_crab_position = Enum.max(crab_positions)
|
||||||
|
crab_frequencies = Enum.frequencies(crab_positions)
|
||||||
|
|
||||||
for position <- 1..max do
|
crab_frequencies
|
||||||
for crab <- crabs do
|
|> cost_of_most_efficient_position(1..max_crab_position, cost_fun)
|
||||||
n = abs(crab - position)
|
end
|
||||||
1 / 2 * n * (n + 1)
|
|
||||||
end
|
def cost_of_most_efficient_position(crab_freqs, range, cost_fun) do
|
||||||
|> Enum.sum()
|
range
|
||||||
end
|
|> Enum.map(&total_fuel_cost_for_position(crab_freqs, &1, cost_fun))
|
||||||
|> Enum.min()
|
|> Enum.min()
|
||||||
|> trunc()
|
|> trunc()
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue