~ihabunek/aoc2019

aoc2019/lib/day19.ex -rw-r--r-- 1.5 KiB
e62d4d9cIvan Habunek Day 18, part 2 10 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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