defmodule Day19 do
import Utils, only: [time: 2, input_file: 1, count_if: 2]
def run() do
time(&part1/0, "Part 1")
time(&part2/0, "Part 2")
end
def part1() do
points = for x <- 0..49, y <- 0..49, do: {x, y}
scan = make_scanner()
count_if(points, scan)
end
def part2() do
scan = make_scanner()
size = 100
size
|> xstream()
|> Stream.map(fn {y2, x1} ->
y1 = y2 - size + 1
x2 = x1 + size - 1
# No need to check bottom left corner again, check others
if scan.({x1, y1}) && scan.({x2, y1}) && scan.({x2, y2}) do
x1 * 10000 + y1
end
end)
|> Enum.find(& &1)
end
@doc """
Returns a stream yielding minimal x positions affected by the beam, per line,
starting with line `y`. Assumes the values are monotonic.
"""
def xstream(y) do
scan = make_scanner()
state = {y, 0}
Stream.iterate(state, fn {y, prev_x} ->
x_min =
prev_x
|> Stream.iterate(&(&1 + 1))
|> Enum.find(&scan.({&1, y}))
{y + 1, x_min}
end)
end
@doc """
Returns a function which takes a point as {x, y} and returns a boolean
wheteher the location is affected by the beam.
"""
def make_scanner() do
machine =
input_file("day19")
|> IntCode.load()
|> IntCode.new()
fn {x, y} ->
{out, _machine} =
machine
|> IntCode.add_input(x)
|> IntCode.add_input(y)
|> IntCode.run_until_output()
out == 1
end
end
end