Skip to content

Commit 5818330

Browse files
committed
day 7: recursion and pattern matching
Signed-off-by: Lakshya Singh <[email protected]>
1 parent c8073ab commit 5818330

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@ Collect stars by solving puzzles. Two puzzles will be made available on each day
2929
| [Day 4: Ceres Search](./lib/advent_of_code/day_04.ex) | 🌟 | 🌟 |
3030
| [Day 5: Print Queue](./lib/advent_of_code/day_05.ex) | 🌟 | 🌟 |
3131
| [Day 6: Guard Gallivant](./lib/advent_of_code/day_06.ex) | 🌟 | |
32+
| [Day 7: Bridge Repair](./lib/advent_of_code/day_07.ex) | 🌟 | 🌟 |

lib/advent_of_code/day_07.ex

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
defmodule AdventOfCode.Day07 do
2+
defp parse_input(input) do
3+
String.split(input, "\n", trim: true)
4+
|> Enum.map(fn line -> String.split(line, ":", trim: true) end)
5+
|> Enum.map(fn [value, raw_list] ->
6+
{String.to_integer(value),
7+
String.split(raw_list, " ", trim: true)
8+
|> Enum.map(fn raw_val -> String.to_integer(raw_val) end)}
9+
end)
10+
end
11+
12+
defp join_numbers(a, b), do: Integer.pow(10, length(Integer.digits(b, 10))) * a + b
13+
14+
@default_options [concat: true]
15+
defp is_possible?(value, numbers, options \\ [])
16+
defp is_possible?(value, [head1, head2 | tail], options) do
17+
options = Keyword.merge(@default_options, options)
18+
is_possible?(value, [head1 + head2 | tail], options) ||
19+
is_possible?(value, [head1 * head2 | tail], options) ||
20+
(options[:concat] && is_possible?(value, [join_numbers(head1, head2) | tail]))
21+
end
22+
defp is_possible?(value, [head1], _options), do: value == head1
23+
24+
def part1(input) do
25+
parse_input(input)
26+
|> Enum.filter(fn {value, numbers} -> is_possible?(value, numbers, concat: false) end)
27+
|> Enum.reduce(0, fn {value, _}, acc -> value + acc end)
28+
end
29+
30+
def part2(input) do
31+
parse_input(input)
32+
|> Enum.filter(fn {value, numbers} -> is_possible?(value, numbers) end)
33+
|> Enum.reduce(0, fn {value, _}, acc -> value + acc end)
34+
end
35+
end

test/day_07_test.exs

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
defmodule AdventOfCode.Day07Test do
2+
use ExUnit.Case, async: true
3+
4+
import AdventOfCode.Day07
5+
6+
setup do
7+
[
8+
input: """
9+
190: 10 19
10+
3267: 81 40 27
11+
83: 17 5
12+
156: 15 6
13+
7290: 6 8 6 15
14+
161011: 16 10 13
15+
192: 17 8 14
16+
21037: 9 7 18 13
17+
292: 11 6 16 20
18+
"""
19+
]
20+
end
21+
22+
test "part1", %{input: input} do
23+
result = part1(input)
24+
25+
assert result == 3749
26+
end
27+
28+
test "part2", %{input: input} do
29+
result = part2(input)
30+
31+
assert result == 11387
32+
end
33+
end

0 commit comments

Comments
 (0)