Day 05
Setup
Mix.install([
{:vega_lite, "~> 0.1.2"},
{:kino, "~> 0.4.1"}
])
input = Kino.Input.textarea("Puzzle Input")
Part 1
input
|> Kino.Input.read()
|> String.split("\n", trim: true)
|> Enum.map(
&(&1
|> String.split([",", " -> "])
|> Enum.map(fn n -> String.to_integer(n) end))
)
|> Enum.filter(fn [x1, y1, x2, y2] -> x1 == x2 or y1 == y2 end)
|> Enum.map(fn coords ->
case coords do
[x, y1, x, y2] ->
for y <- y1..y2, do: {x, y}
[x1, y, x2, y] ->
for x <- x1..x2, do: {x, y}
end
end)
|> List.flatten()
|> Enum.frequencies()
|> Map.values()
|> Enum.count(&(&1 > 1))
Part 2
input
|> Kino.Input.read()
|> String.split("\n", trim: true)
|> Enum.map(
&(&1
|> String.split([",", " -> "])
|> Enum.map(fn n -> String.to_integer(n) end))
)
|> Enum.map(fn [x1, y1, x2, y2] ->
cond do
x1 == x2 ->
for y <- y1..y2, do: {x1, y}
y1 == y2 ->
for x <- x1..x2, do: {x, y1}
x1 - x2 == y1 - y2 or x1 - x2 == (y1 - y2) * -1 ->
Enum.zip(x1..x2, y1..y2)
true ->
[]
end
end)
|> List.flatten()
|> Enum.frequencies()
|> Map.values()
|> Enum.count(&(&1 > 1))
Part 2 Refactor
input
|> Kino.Input.read()
|> String.split("\n", trim: true)
|> Enum.map(
&(&1
|> String.split([",", " -> "])
|> Enum.map(fn n -> String.to_integer(n) end))
)
|> Enum.flat_map(fn
[x, y1, x, y2] -> Enum.zip(Stream.cycle([x]), y1..y2)
[x1, y, x2, y] -> Enum.zip(x1..x2, Stream.cycle([y]))
[x1, y1, x2, y2] -> Enum.zip(x1..x2, y1..y2)
end)
|> Enum.frequencies()
|> Map.values()
|> Enum.count(&(&1 > 1))
VegaLite
alias VegaLite, as: Vl
data =
input
|> Kino.Input.read()
|> String.split("\n", trim: true)
|> Enum.map(
&(&1
|> String.split([",", " -> "])
|> Enum.map(fn n -> String.to_integer(n) end))
)
|> Enum.flat_map(fn
[x, y1, x, y2] -> Enum.zip(Stream.cycle([x]), y1..y2)
[x1, y, x2, y] -> Enum.zip(x1..x2, Stream.cycle([y]))
[x1, y1, x2, y2] -> Enum.zip(x1..x2, y1..y2)
end)
|> Enum.map(fn {x, y} -> %{x: x, y: y} end)
Vl.new(width: 400, height: 400, background: "white")
|> Vl.data_from_values(data)
|> Vl.mark(:circle)
|> Vl.encode_field(:x, "x", axis: [title: "x"], bin: [maxbins: 50])
|> Vl.encode_field(:y, "y", axis: [title: "y"], bin: [maxbins: 50])
|> Vl.encode(:size, aggregate: :count)
|> Vl.encode(:color, aggregate: :count, scale: [range: ["green", "red"]])