Skip to content

Commit 35a6833

Browse files
committed
Complete day 6 part 2
1 parent 31fdef4 commit 35a6833

File tree

1 file changed

+41
-5
lines changed

1 file changed

+41
-5
lines changed

day6.exs

+41-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
defmodule Day6 do
1+
defmodule Day6.Part1 do
22
@regex ~r/(?<command>\w*?\s?\w*) (?<top_x>\d*),(?<top_y>\d*) through (?<bottom_x>\d*),(?<bottom_y>\d*)/
33

44
# Puts in instructions in the format {:command, {top_tuple}, {bottom_tuple}}
@@ -10,7 +10,11 @@ defmodule Day6 do
1010
end
1111
end
1212

13-
def follow_instructions(instructions) do
13+
def total_on(instructions) do
14+
follow_instructions(instructions) |> Dict.values |> Enum.filter(&(&1 == true)) |> Enum.count
15+
end
16+
17+
defp follow_instructions(instructions) do
1418
coordinates = Enum.flat_map 0..999, fn x ->
1519
Enum.map 0..999, fn y -> {x, y} end
1620
end
@@ -37,10 +41,42 @@ defmodule Day6 do
3741
defp handle_instruction(:toggle, current), do: !current
3842
end
3943

44+
defmodule Day6.Part2 do
45+
def total_brightness(instructions) do
46+
follow_instructions(instructions) |> Dict.values |> Enum.sum
47+
end
48+
49+
defp follow_instructions(instructions) do
50+
coordinates = Enum.flat_map 0..999, fn x ->
51+
Enum.map 0..999, fn y -> {x, y} end
52+
end
53+
lights = Enum.reduce coordinates, HashDict.new, fn coordinate, acc ->
54+
Dict.put(acc, coordinate, 0)
55+
end
56+
57+
Enum.reduce instructions, lights, fn {instruction, top, bottom}, lights ->
58+
change_lights(lights, instruction, top, bottom)
59+
end
60+
end
61+
62+
defp change_lights(lights, instruction, {top_x, top_y}, {bottom_x, bottom_y}) do
63+
coordinates = Enum.flat_map top_x..bottom_x, fn x ->
64+
Enum.map top_y..bottom_y, fn y -> {x, y} end
65+
end
66+
Enum.reduce coordinates, lights, fn coordinate, lights ->
67+
Dict.update!(lights, coordinate, fn current -> handle_instruction(instruction, current) end)
68+
end
69+
end
70+
71+
defp handle_instruction(:turn_on, current), do: current + 1
72+
defp handle_instruction(:turn_off, current), do: max(0, current - 1)
73+
defp handle_instruction(:toggle, current), do: current + 2
74+
end
75+
4076
{:ok, input} = File.read("input/day6.txt")
4177
parsed_instructions = input
4278
|> String.split("\n")
43-
|> Day6.parse_instructions
79+
|> Day6.Part1.parse_instructions
4480

45-
#val = Day6.start([{:turn_on, {0, 0}, {999, 999}}])
46-
IO.inspect(Day6.follow_instructions(parsed_instructions) |> Dict.values |> Enum.filter(&(&1 == true)) |> Enum.count)
81+
IO.inspect Day6.Part1.total_on(parsed_instructions)
82+
IO.inspect Day6.Part2.total_brightness(parsed_instructions)

0 commit comments

Comments
 (0)