-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_09.ex
53 lines (44 loc) · 1.3 KB
/
day_09.ex
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 AdventOfCode.Y2023.Day09 do
@moduledoc """
--- Day 9: Mirage Maintenance ---
Problem Link: https://adventofcode.com/2023/day/9
Difficulty: xs
Tags: sequence reduction
"""
alias AdventOfCode.Helpers.{InputReader, Transformers}
def input, do: InputReader.read_from_file(2023, 9)
def run(input \\ input()) do
input = parse(input)
{extrapolate_by(input, &forward/1), extrapolate_by(input, &backward/1)}
end
def extrapolate_by(histories, direction_fn),
do: Enum.reduce(histories, 0, fn x, acc -> acc + direction_fn.(x) end)
def parse(data \\ input()) do
for line <- Transformers.lines(data), do: Transformers.int_words(line)
end
defp forward(data) do
extrapolate(data, [data], fn acc ->
Enum.sum_by(acc, &List.last/1)
end)
end
defp backward(data) do
extrapolate(data, [data], fn acc ->
acc
|> Enum.map(&hd/1)
|> Enum.reduce(fn x, acc ->
x - acc
end)
end)
end
defp extrapolate(histories, acc, direction_fn) do
case MapSet.size(MapSet.new(histories)) do
1 ->
direction_fn.(acc)
_ ->
histories
|> Enum.chunk_every(2, 1, :discard)
|> Enum.map(fn [a, b] -> b - a end)
|> then(fn record -> extrapolate(record, [record | acc], direction_fn) end)
end
end
end