Skip to content

Commit

Permalink
day 9
Browse files Browse the repository at this point in the history
  • Loading branch information
krystiangryczon committed Dec 9, 2023
1 parent 83b951c commit f393e33
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 8 deletions.
13 changes: 11 additions & 2 deletions lib/advent_of_code/day_09.ex
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
defmodule AdventOfCode.Day09 do
def part1(_args) do
alias Advent.D09_01
alias Advent.D09_02

def part1(inp) do
D09_01.parse_input(inp)
|> Enum.reduce(0, fn el, acc -> acc + (List.last(el) + D09_01.extrapolate(el, 0)) end)
end

def part2(_args) do
def part2(inp) do
D09_01.parse_input(inp)
|> Enum.reduce(0, fn el, acc ->
acc + (List.first(el) - D09_02.get_left_val(D09_02.extrapolate(el, []), 0))
end)
end
end
33 changes: 33 additions & 0 deletions lib/code/day9_1.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
defmodule Advent.D09_01 do
defp calc_next([], next), do: next

defp calc_next(curr, next) do
if(length(curr) > 1) do
[h | t] = curr
[h2 | _] = t
calc_next(t, [h - h2 | next])
else
next
end
end

def extrapolate(line, acc) do
if(Enum.all?(line, fn el -> el == 0 end)) do
acc
else
next = calc_next(Enum.reverse(line), [])
extrapolate(next, acc + List.last(next))
end
end

@sep "\n"
def parse_input(inp) do
inp
|> String.split(@sep, trim: true)
|> Enum.map(fn sublist ->
Enum.map(String.split(sublist, " ", trim: true), fn el ->
My.Utils.string_to_num_or_false(el)
end)
end)
end
end
33 changes: 33 additions & 0 deletions lib/code/day9_2.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
defmodule Advent.D09_02 do
defp calc_next([], next), do: next

defp calc_next(curr, next) do
if(length(curr) > 1) do
[h | t] = curr
[h2 | _] = t
calc_next(t, [h2 - h | next])
else
next
end
end

def extrapolate(line, res) do
if(Enum.all?(line, fn el -> el == 0 end)) do
res
else
next = Enum.reverse(calc_next(line, []))
extrapolate(next, [List.first(next)] ++ res)
end
end

def get_left_val([], acc), do: acc

def get_left_val(vals, acc) do
if(length(vals) > 0) do
[f | values] = vals
get_left_val(values, f - acc)
else
acc
end
end
end
17 changes: 11 additions & 6 deletions test/advent_of_code/day_09_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,24 @@ defmodule AdventOfCode.Day09Test do

import AdventOfCode.Day09

@tag :skip
def test_input(),
do: """
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
"""

test "part1" do
input = nil
input = test_input()
result = part1(input)

assert result
assert result == 114
end

@tag :skip
test "part2" do
input = nil
input = test_input()
result = part2(input)

assert result
assert result == 2
end
end

0 comments on commit f393e33

Please sign in to comment.