Skip to content

Commit

Permalink
day 6
Browse files Browse the repository at this point in the history
  • Loading branch information
krystiangryczon committed Dec 6, 2023
1 parent 103fd78 commit e3e3af3
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 8 deletions.
6 changes: 4 additions & 2 deletions lib/advent_of_code/day_06.ex
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
defmodule AdventOfCode.Day06 do
def part1(_args) do
def part1(inp) do
Advent.Code6_1.execute(inp)
end

def part2(_args) do
def part2(inp) do
Advent.Code6_1.execute(inp)
end
end
34 changes: 34 additions & 0 deletions lib/code/day6_1.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
defmodule Advent.Code6_1 do
@sep "\n"
defp parse_input(inp, sep) do
[time, distance] =
String.split(inp, sep, trim: true)
|> Enum.map(fn el -> String.split(el, ~r/[(Time:)(Distance:)]/) end)
|> Enum.map(fn sublist -> Enum.filter(sublist, fn el -> String.length(el) != 0 end) end)
|> Enum.map(fn sublist ->
Enum.map(sublist, fn el -> String.split(el, " ", trim: true) end)
end)
|> Enum.flat_map(fn el -> el end)
|> Enum.map(fn sublist ->
Enum.map(sublist, fn el -> My.Utils.string_to_num_or_false(el) end) |> Enum.with_index()
end)

time
|> Enum.map(fn {t_el, idx} ->
{d_el, idx} = Enum.at(distance, idx)
%{time: t_el, distance: d_el, idx: idx}
end)
end

defp calculate(row) do
Enum.to_list(0..row[:time])
|> Enum.filter(fn el -> el * (row[:time] - el) > row[:distance] end)
|> Enum.count()
end

def execute(inp) do
parse_input(inp, @sep)
|> Enum.map(fn el -> calculate(el) end)
|> Enum.reduce(fn el, acc -> acc * el end)
end
end
22 changes: 16 additions & 6 deletions test/advent_of_code/day_06_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,29 @@ defmodule AdventOfCode.Day06Test do

import AdventOfCode.Day06

@tag :skip
def test_input1(),
do: """
Time: 7 15 30
Distance: 9 40 200
"""

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

assert result
assert result == 288
end

@tag :skip
def test_input2(),
do: """
Time: 71530
Distance: 940200
"""

test "part2" do
input = nil
input = test_input2()
result = part2(input)

assert result
assert result == 71503
end
end

0 comments on commit e3e3af3

Please sign in to comment.