Skip to content

Instantly share code, notes, and snippets.

@AntonFagerberg
Created January 7, 2016 16:40
Show Gist options
  • Save AntonFagerberg/15f305b6ec5cd5193b32 to your computer and use it in GitHub Desktop.
Save AntonFagerberg/15f305b6ec5cd5193b32 to your computer and use it in GitHub Desktop.
inputs = ["turn on 499,499 through 500,500"]
res = inputs |> Enum.reduce(%{}, fn (input, acc) ->
[[_, cmd, x1, y1, x2, y2]] = Regex.scan(~r/(turn (?:on|off)|toggle) (\d+),(\d+) through (\d+),(\d+)/, input)
x1 = String.to_integer(x1)
x2 = String.to_integer(x2)
y1 = String.to_integer(y1)
y2 = String.to_integer(y2)
offset = 1_000_000
Enum.reduce(x1..x2, acc, fn (x, x_acc) ->
Enum.reduce(y1..y2, x_acc, fn (y, y_acc) ->
Dict.get_and_update(y_acc, x + y * offset, fn (current) ->
if (current == nil), do: current = 0
case cmd do
"turn on" ->
{nil, current + 1}
"turn off" ->
if current > 0 do
{nil, current - 1}
else
{nil, 0}
end
"toggle" ->
{nil, current + 2}
end
end)
|> elem(1)
end)
end)
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment