Skip to content

Instantly share code, notes, and snippets.

@ignaciovazquez
Last active December 8, 2015 00:14
Show Gist options
  • Save ignaciovazquez/bc749a9016b5b10e1f5f to your computer and use it in GitHub Desktop.
Save ignaciovazquez/bc749a9016b5b10e1f5f to your computer and use it in GitHub Desktop.
Advent of Code. Day 6 - Part 2.
parse_command = fn command ->
{cmd, rest} = case command do
<<"turn on ", rest :: binary>> -> {:on, rest}
<<"turn off ", rest :: binary>> -> {:off, rest}
<<"toggle ", rest :: binary>> -> {:toggle, rest}
end
[x1y1, _, x2y2] = String.split(rest)
[x1, y1] = String.split(x1y1, ",") |> Enum.map(&(String.to_integer(&1)))
[x2, y2] = String.split(x2y2, ",") |> Enum.map(&(String.to_integer(&1)))
{cmd, min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2) }
end
generate_coordinates = fn x1, y1, x2, y2 ->
Enum.flat_map(x1..x2, fn x ->
Enum.map(y1..y2, fn y ->
{x, y}
end)
end)
end
fill_map = fn map, cmd, x1, y1, x2, y2 ->
Enum.reduce(generate_coordinates.(x1, y1, x2, y2), map, fn {x, y}, map ->
map = case cmd do
:on -> Dict.update(map, {x, y}, 1, &(&1 + 1))
:off -> Dict.update(map, {x, y}, 0, &(if (&1 > 0) do &1 - 1 else &1 end))
:toggle -> Dict.update(map, {x, y}, 2, &(&1 + 2))
end
map
end)
end
input_stream = File.stream!("input.txt")
final_map = Enum.reduce(input_stream, %{}, fn line, light_map ->
{cmd, x1, y1, x2, y2} = parse_command.(line |> String.strip)
light_map = fill_map.(light_map, cmd, x1, y1, x2, y2)
light_map
end)
total_brightness = Enum.reduce(final_map, 0, fn {_, brightness}, acc ->
acc + brightness
end)
IO.puts "Total brightness: #{total_brightness}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment