Skip to content

Commit a5e08fd

Browse files
committed
More idiomatic Elixir
1 parent 09824dd commit a5e08fd

2 files changed

Lines changed: 13 additions & 43 deletions

File tree

2025/lib/day07/day07.ex

Lines changed: 13 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,21 @@ defmodule Day07 do
55
|> File.read!()
66
|> String.split("\n", trim: true)
77

8+
# I don't totally get this for comprehension
89
splitters =
9-
lines
10-
|> Enum.with_index()
11-
|> Enum.flat_map(fn {line, y} ->
12-
line
13-
|> String.graphemes()
14-
|> Enum.with_index()
15-
|> Enum.flat_map(fn
16-
{"^", x} -> [{x, y}]
17-
_ -> []
18-
end)
19-
end)
20-
|> MapSet.new()
10+
for {line, y} <- Enum.with_index(lines),
11+
{char, x} <- Enum.with_index(String.graphemes(line)),
12+
char == "^",
13+
into: MapSet.new() do
14+
{x, y}
15+
end
2116

2217
[first_line | _] = lines
2318

2419
start_x =
2520
first_line
2621
|> String.graphemes()
27-
|> Enum.find_index(fn char -> char == "S" end)
22+
|> Enum.find_index(&(&1 == "S"))
2823

2924
max_y = length(lines) - 1
3025

@@ -47,29 +42,15 @@ defmodule Day07 do
4742
end)
4843
end
4944

50-
def increment_map(m, keys, incr) do
51-
Enum.reduce(keys, m, fn k, acc ->
52-
{_, new_m} =
53-
Map.get_and_update(acc, k, fn cur ->
54-
if cur == nil do
55-
{cur, incr}
56-
else
57-
{cur, cur + incr}
58-
end
59-
end)
60-
61-
new_m
62-
end)
63-
end
64-
6545
def quantum_split_row(splitters, beams, y) do
6646
beams
6747
|> Enum.reduce(%{}, fn {{b_x, _}, b_c}, new_beams ->
6848
if MapSet.member?(splitters, {b_x, y}) do
69-
new_beams = increment_map(new_beams, [{b_x - 1, y}, {b_x + 1, y}], b_c)
7049
new_beams
50+
|> Map.update({b_x - 1, y}, b_c, &(&1 + b_c))
51+
|> Map.update({b_x + 1, y}, b_c, &(&1 + b_c))
7152
else
72-
increment_map(new_beams, [{b_x, y}], b_c)
53+
Map.update(new_beams, {b_x, y}, b_c, &(&1 + b_c))
7354
end
7455
end)
7556
end
@@ -89,9 +70,8 @@ defmodule Day07 do
8970
def part2(infile) do
9071
{start, splitters, max_y} = input(infile)
9172

92-
Enum.reduce(1..max_y, %{start => 1}, fn y, beams ->
93-
quantum_split_row(splitters, beams, y)
94-
end)
73+
1..max_y
74+
|> Enum.reduce(%{start => 1}, &quantum_split_row(splitters, &2, &1))
9575
|> Map.values()
9676
|> Enum.sum()
9777
end

2025/test/day07/day07_test.exs

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,6 @@ defmodule Day07Test do
5151
assert MapSet.to_list(new_beams) == [{6, 2}, {8, 2}]
5252
end
5353

54-
test "increment_map" do
55-
a = Day07.increment_map(%{}, [:a, :b], 1)
56-
assert a[:a] == 1
57-
assert a[:b] == 1
58-
59-
b = Day07.increment_map(%{a: 2, b: 3}, [:a, :b], 1)
60-
assert b[:a] == 3
61-
assert b[:b] == 4
62-
end
63-
6454
test "quantum_split_row", %{temp_file: temp_file} do
6555
{start, splitters, _} = Day07.input(temp_file)
6656
beams = %{start => 1}

0 commit comments

Comments
 (0)