Skip to content

Instantly share code, notes, and snippets.

@ignaciovazquez
Last active December 8, 2015 00:14
Show Gist options
  • Save ignaciovazquez/b232e6551e188ebc358e to your computer and use it in GitHub Desktop.
Save ignaciovazquez/b232e6551e188ebc358e to your computer and use it in GitHub Desktop.
Advent of Code. Day 6 - Part 1.
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.put(map, {x, y}, true)
:off -> Dict.put(map, {x, y}, false)
:toggle -> Dict.update(map, {x, y}, true, &(!&1))
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)
lights_on = Enum.count(final_map, fn {_, val} -> val end)
IO.puts "Total number of lights on: #{lights_on}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment