Greetings, fantastic folks! Ukrainian Erlanger reporting in ! As we transition into the weekend, today marks the advent of Day 9 in our thrilling journey through the Advent of Code. A fresh puzzle awaits, ready to challenge and inspire! Don’t forget to share your ingenious code solutions in the comments below. Embrace the spirit of discovery and coding joy. Happy Saturday, and happy coding, everyone!
3 Likes
My day 9 solution:
defmodule Aoc.Nine do
def parse(string) do
string
|> String.split("\n", trim: true)
|> Enum.map(fn line ->
line |> String.split(" ", trim: true) |> Enum.map(&String.to_integer/1)
end)
end
def part_one(input) do
input
|> Enum.map(&reduce/1)
|> Enum.unzip()
|> elem(0)
|> Enum.sum()
end
def part_two(input) do
input
|> Enum.map(&reduce/1)
|> Enum.unzip()
|> elem(1)
|> Enum.sum()
end
def reduce([first|_] = list) do
reduce(list, [], first)
end
def reduce([a, b | rest], acc, c) do
reduce([b | rest], [b - a | acc], c)
end
def reduce([a], [b | _] = acc, c) do
if Enum.all?(acc, &(&1 == a)) do
{a + b, c - b}
else
{new_b, new_c} = reduce(Enum.reverse(acc))
{a + new_b, c - new_c}
end
end
end
input = File.read!("priv/9.txt") |> Aoc.Nine.parse()
input |> Aoc.Nine.part_one() |> IO.inspect(label: "part 1")
input |> Aoc.Nine.part_two() |> IO.inspect(label: "part 2")
1 Like
My Day 9 solution: https://github.com/wfvining/aoc2023/blob/main/day9/day9.erl
1 Like
1 Like