Skip to content

Commit 35c3d50

Browse files
committed
Solve 2021/12
1 parent f3a65b3 commit 35c3d50

3 files changed

Lines changed: 90 additions & 0 deletions

File tree

lib/2021/day_12.ex

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
defmodule AdventOfCode.Y2021.Day12 do
2+
@moduledoc """
3+
--- Day 12: Passage Pathing ---
4+
Problem Link: https://adventofcode.com/2021/day/12
5+
Difficulty: m
6+
Tags: graph traversal recursion path-finding
7+
"""
8+
alias AdventOfCode.Helpers.{InputReader, Transformers}
9+
10+
def input, do: InputReader.read_from_file(2021, 12)
11+
12+
def run(input \\ input()) do
13+
graph = parse(input)
14+
15+
p1 = count_paths(graph, "start", MapSet.new(), false)
16+
p2 = count_paths(graph, "start", MapSet.new(), true)
17+
18+
{p1, p2}
19+
end
20+
21+
defp count_paths(_graph, "end", _visited, _allow_double), do: 1
22+
23+
defp count_paths(graph, current, visited, allow_double) do
24+
next_visited = if small?(current), do: MapSet.put(visited, current), else: visited
25+
26+
Yog.neighbors(graph, current)
27+
|> Enum.reduce(0, fn {neighbor, _}, total ->
28+
cond do
29+
neighbor == "start" ->
30+
total
31+
32+
not small?(neighbor) or not MapSet.member?(visited, neighbor) ->
33+
total + count_paths(graph, neighbor, next_visited, allow_double)
34+
35+
allow_double ->
36+
total + count_paths(graph, neighbor, next_visited, false)
37+
38+
true ->
39+
total
40+
end
41+
end)
42+
end
43+
44+
defp small?(node), do: String.downcase(node) == node
45+
46+
def parse(data \\ input()) do
47+
data
48+
|> Transformers.lines()
49+
|> Enum.reduce(Yog.undirected(), fn line, graph ->
50+
[u, v] = String.split(line, "-")
51+
Yog.add_edge_ensure(graph, u, v, 1)
52+
end)
53+
end
54+
end

priv/input_files/2021_12.txt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
EG-bj
2+
LN-end
3+
bj-LN
4+
yv-start
5+
iw-ch
6+
ch-LN
7+
EG-bn
8+
OF-iw
9+
LN-yv
10+
iw-TQ
11+
iw-start
12+
TQ-ch
13+
EG-end
14+
bj-OF
15+
OF-end
16+
TQ-start
17+
TQ-bj
18+
iw-LN
19+
EG-ch
20+
yv-iw
21+
KW-bj
22+
OF-ch
23+
bj-ch
24+
yv-TQ

test/2021/day_12_test.exs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
defmodule AdventOfCode.Y2021.Day12Test do
2+
@moduledoc false
3+
4+
use ExUnit.Case, async: true
5+
@moduletag :y2112
6+
7+
alias AdventOfCode.Y2021.Day12, as: Solution
8+
9+
test "Year 2021, Day 12 run/1" do
10+
assert Solution.run() == {4659, 148_962}
11+
end
12+
end

0 commit comments

Comments
 (0)