summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJustin Wernick <justin@worthe-it.co.za>2024-09-13 15:49:18 +0200
committerJustin Wernick <justin@worthe-it.co.za>2024-09-13 15:49:18 +0200
commitba515a6a1396f1f4932cbec80f0dc52caa761052 (patch)
tree0a19a69f08ddb275fa1b6a3bccecb9b4b08e04bc
parenta85255e0a182817b3de724527a0d0fb26619809f (diff)
Day 6
-rw-r--r--2015/day6.exs87
1 files changed, 87 insertions, 0 deletions
diff --git a/2015/day6.exs b/2015/day6.exs
new file mode 100644
index 0000000..9ad62cd
--- /dev/null
+++ b/2015/day6.exs
@@ -0,0 +1,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}")