aboutsummaryrefslogtreecommitdiff
path: root/day15/part2.rb
blob: cb3219d559a184786064cf531892ca1386d061ba (plain)
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
class Sensor
  def initialize(sx, sy, bx, by)
    @x = sx
    @y = sy
    @range = dist(bx, by)
  end

  attr_reader :x, :y, :range

  def dist(x, y)
    (@x - x).abs + (@y - y).abs
  end

  def cover?(x, y)
    dist(x, y) <= @range
  end

  def edge
    edges = []
    at = [@x, @y - (@range + 1)]
    until at[1] == @y
      edges << at
      at[0] += 1
      at[1] += 1
    end
    until at[0] == @x
      edges << at
      at[0] -= 1
      at[1] += 1
    end
    until at[1] == @y
      edges << at
      at[0] -= 1
      at[1] -= 1
    end
    until at[0] == @x
      edges << at
      at[0] += 1
      at[1] -= 1
    end
    edges
  end
end

sensors = []
$stdin.readlines.each do |line|
  c = line.scan(/x=(-?\d+), y=(-?\d+)/).flatten.map(&:to_i)
  sensors << Sensor.new(*c)
end

max = 4_000_000

coord = sensors.map { |s|
  s.edge.reject { |e|
    e[0] < 0 || e[0] > max ||
    e[1] < 0 || e[1] > max ||
    sensors.any? { |s2| s2.cover?(*e) }
  }
}.flatten(1).uniq[0]

puts coord[0] * 4_000_000 + coord[1]