Advent of Code 2021 - Day 7
Setup
Mix.install([
{:kino, "~> 0.4.1"}
])
:ok
example_input = Kino.Input.textarea("Please enter the example input:")
my_input = Kino.Input.textarea("Please enter your input:")
defmodule Parser do
def parse_input(input) do
input
|> String.split(",", trim: true)
|> Enum.map(&String.to_integer/1)
end
end
example_input =
example_input
|> Kino.Input.read()
|> Parser.parse_input()
my_input =
my_input
|> Kino.Input.read()
|> Parser.parse_input()
:ok
:ok
Part 1
defmodule Day7.Part1 do
def solve(input) do
{min, max} = Enum.min_max(input)
min..max
|> Enum.map(fn target_position ->
input
|> Enum.map(&abs(&1 - target_position))
|> Enum.sum()
end)
|> Enum.min()
end
end
Day7.Part1.solve(my_input)
336721
Part 2
defmodule Day7.Part2 do
def solve(input) do
{min, max} = Enum.min_max(input)
min..max
|> Enum.map(fn target_position ->
input
|> Enum.map(&abs(&1 - target_position))
|> Enum.map(&fuel_cost/1)
|> Enum.sum()
end)
|> Enum.min()
end
defp fuel_cost(distance) do
distance * (distance + 1) / 2
end
end
Day7.Part2.solve(my_input)
91638945.0