Skip to content

Commit c4272cb

Browse files
committed
day09
1 parent 5f293bb commit c4272cb

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

09/sample_input

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
0 3 6 9 12 15
2+
1 3 6 10 15 21
3+
10 13 16 21 30 45

09/sol.exs

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
defmodule Day09 do
2+
defp read_input(file_path) do
3+
case File.read(file_path) do
4+
{:ok, content} ->
5+
content
6+
|> String.split("\n", trim: true)
7+
|> Enum.map(&String.split(&1, " ", trim: true))
8+
|> Enum.map(fn x -> Enum.map(x, &String.to_integer/1) end)
9+
10+
{:error, reason} ->
11+
raise "Oh no! #{reason}"
12+
end
13+
end
14+
15+
defp extrapolate(xs) do
16+
if Enum.all?(xs, fn x -> x == 0 end) do
17+
0
18+
else
19+
0..(length(xs) - 2)
20+
|> Enum.map(fn i -> Enum.at(xs, i + 1) - Enum.at(xs, i) end)
21+
|> (&(hd(Enum.take(xs, -1)) + extrapolate(&1))).()
22+
end
23+
end
24+
25+
def partA(file_path) do
26+
read_input(file_path)
27+
|> Enum.map(&extrapolate/1)
28+
|> Enum.sum()
29+
end
30+
31+
def partB(file_path) do
32+
read_input(file_path)
33+
|> Enum.map(&extrapolate(Enum.reverse(&1)))
34+
|> Enum.sum()
35+
end
36+
end
37+
38+
IO.puts(Day09.partA("./input"))
39+
IO.puts(Day09.partB("./input"))

0 commit comments

Comments
 (0)