1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
instructions = File.stream!("inputs/day6.txt")
regex = ~r/(toggle|turn off|turn on) ([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)/
endLights1 =
Enum.reduce(instructions, MapSet.new(), fn instruction, acc ->
[_, action, x1, y1, x2, y2] = Regex.run(regex, instruction)
{x1, ""} = Integer.parse(x1)
{x2, ""} = Integer.parse(x2)
{y1, ""} = Integer.parse(y1)
{y2, ""} = Integer.parse(y2)
case action do
"toggle" ->
for x <- x1..x2, y <- y1..y2, reduce: acc do
acc ->
if MapSet.member?(acc, {x, y}) do
MapSet.delete(acc, {x, y})
else
MapSet.put(acc, {x, y})
end
end
"turn off" ->
for x <- x1..x2, y <- y1..y2, reduce: acc do
acc -> MapSet.delete(acc, {x, y})
end
"turn on" ->
for x <- x1..x2, y <- y1..y2, reduce: acc do
acc -> MapSet.put(acc, {x, y})
end
end
end)
litLights1 = MapSet.size(endLights1)
IO.puts("Lit lights count 1: #{litLights1}")
min = 0
max = 999
startLights2 =
for x <- min..max, y <- min..max, reduce: Map.new() do
acc -> Map.put(acc, {x, y}, 0)
end
endLights2 =
Enum.reduce(instructions, startLights2, fn instruction, acc ->
[_, action, x1, y1, x2, y2] = Regex.run(regex, instruction)
{x1, ""} = Integer.parse(x1)
{x2, ""} = Integer.parse(x2)
{y1, ""} = Integer.parse(y1)
{y2, ""} = Integer.parse(y2)
case action do
"toggle" ->
for x <- x1..x2, y <- y1..y2, reduce: acc do
acc ->
{_, acc} = Map.get_and_update!(acc, {x, y}, fn i -> {i, i + 2} end)
acc
end
"turn off" ->
for x <- x1..x2, y <- y1..y2, reduce: acc do
acc ->
{_, acc} =
Map.get_and_update!(acc, {x, y}, fn
0 -> {0, 0}
i -> {i, i - 1}
end)
acc
end
"turn on" ->
for x <- x1..x2, y <- y1..y2, reduce: acc do
acc ->
{_, acc} = Map.get_and_update!(acc, {x, y}, fn i -> {i, i + 1} end)
acc
end
end
end)
lightIntensity2 = Map.values(endLights2) |> Enum.sum()
IO.puts("Lit lights intensity 2: #{lightIntensity2}")
|