122 lines
2 KiB
Markdown
122 lines
2 KiB
Markdown
# AOC 2022 - Template - fork
|
|
|
|
```elixir
|
|
Mix.install([
|
|
{:req, "~> 0.3.3"}
|
|
])
|
|
```
|
|
|
|
## Puzzle description
|
|
|
|
[Day 4: Camp Cleanup](https://adventofcode.com/2022/day/4).
|
|
|
|
## Input
|
|
|
|
```elixir
|
|
defmodule Load do
|
|
def input do
|
|
aoc_session = System.fetch_env!("LB_AOC_SESSION")
|
|
input_url = "https://adventofcode.com/2022/day/4/input"
|
|
Req.get!(input_url, headers: [cookie: "session=#{aoc_session}"]).body
|
|
end
|
|
end
|
|
```
|
|
|
|
## Solution
|
|
|
|
```elixir
|
|
defmodule Util do
|
|
def process(input) do
|
|
input
|
|
|> String.trim()
|
|
|> String.split("\n", trim: true)
|
|
|> Enum.map(&pairs_to_range/1)
|
|
end
|
|
|
|
defp pairs_to_range(pairs) do
|
|
pairs
|
|
|> String.split(",")
|
|
|> Enum.map(&to_range/1)
|
|
end
|
|
|
|
defp to_range(pair) do
|
|
pair =
|
|
pair
|
|
|> String.split("-")
|
|
|> Enum.map(&String.to_integer/1)
|
|
|
|
apply(Range, :new, pair)
|
|
end
|
|
end
|
|
```
|
|
|
|
```elixir
|
|
defmodule Part1 do
|
|
def run(input) do
|
|
input
|
|
|> Util.process()
|
|
|> Enum.reduce(0, fn [first, second], acc ->
|
|
first = MapSet.new(first)
|
|
second = MapSet.new(second)
|
|
|
|
if MapSet.subset?(first, second) or MapSet.subset?(second, first) do
|
|
acc + 1
|
|
else
|
|
acc
|
|
end
|
|
end)
|
|
end
|
|
end
|
|
|
|
defmodule Part2 do
|
|
def run(input) do
|
|
input
|
|
|> Util.process()
|
|
|> Enum.reduce(0, fn [first, second], acc ->
|
|
first = MapSet.new(first)
|
|
second = MapSet.new(second)
|
|
|
|
if MapSet.disjoint?(first, second) do
|
|
acc
|
|
else
|
|
acc + 1
|
|
end
|
|
end)
|
|
end
|
|
end
|
|
|
|
ExUnit.start(autorun: false)
|
|
|
|
defmodule Test do
|
|
use ExUnit.Case, async: true
|
|
@example_input ~s(2-4,6-8
|
|
2-3,4-5
|
|
5-7,7-9
|
|
2-8,3-7
|
|
6-6,4-6
|
|
2-6,4-8)
|
|
@input Load.input()
|
|
|
|
test "it loads the input" do
|
|
assert String.length(@input) > 0
|
|
end
|
|
|
|
test "part 1 example" do
|
|
assert Part1.run(@example_input) === 2
|
|
end
|
|
|
|
test "part 1" do
|
|
assert Part1.run(@input) === 441
|
|
end
|
|
|
|
test "part 2 example" do
|
|
assert Part2.run(@example_input) === 4
|
|
end
|
|
|
|
test "part 2" do
|
|
assert Part2.run(@input) === 861
|
|
end
|
|
end
|
|
|
|
ExUnit.run()
|
|
```
|