Skip to content

Instantly share code, notes, and snippets.

@jemmyw
Created December 8, 2018 04:30
Show Gist options
  • Save jemmyw/d49617622ffd9eb5735fe28329873eb1 to your computer and use it in GitHub Desktop.
Save jemmyw/d49617622ffd9eb5735fe28329873eb1 to your computer and use it in GitHub Desktop.
defmodule Squares do
def parse([]), do: []
def parse([h | t]) do
[parse(h) | parse(t)]
end
def parse(str) do
~r/^#(\d+)\s+@\s+(\d+),(\d+):\s+(\d+)x(\d+)$/
|> Regex.run(str)
|> List.delete_at(0)
|> Enum.map(&String.to_integer(&1))
|> List.to_tuple()
end
def gen_map(claims) do
claims |> Enum.reduce(%{}, fn claim, map -> add_claim(map, claim) end)
end
def count_over(map) do
map |> Enum.filter(fn {_, c} -> c > 1 end) |> Enum.count()
end
def claim_keys({_, x, y, w, h}) do
x..(x + w - 1)
|> Enum.reduce([], fn x, list ->
y..(y + h - 1)
|> Enum.reduce(list, fn y, list ->
[{x, y} | list]
end)
end)
end
def add_claim(map, claim) do
claim
|> claim_keys()
|> Enum.reduce(map, fn key, map ->
Map.put(map, key, Map.get(map, key, 0) + 1)
end)
end
def claim_collision_count(map, claim) do
claim_keys(claim)
|> Enum.reduce(0, fn key, acc ->
max(acc, Map.get(map, key, 0))
end)
end
end
claims =
File.read("3.txt")
|> elem(1)
|> String.split("\n")
|> Enum.reject(fn str -> str == "" end)
|> Squares.parse()
map = Squares.gen_map(claims)
# Part 1
map |> Squares.count_over() |> IO.inspect()
# Part 2
claims
|> Enum.find(nil, fn claim ->
map |> Squares.claim_collision_count(claim) == 1
end)
|> IO.inspect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment