aboutsummaryrefslogtreecommitdiff
path: root/day15/part2.rb
blob: e7ba5d31bcd5d8a61ca464a95da5b2ba736d77f0 (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
62
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 = []
    atx = @x
    aty = @y - (@range + 1)
    until aty == @y
      edges << [atx, aty]
      atx += 1
      aty += 1
    end
    until atx == @x
      edges << [atx, aty]
      atx -= 1
      aty += 1
    end
    until aty == @y
      edges << [atx, aty]
      atx -= 1
      aty -= 1
    end
    until atx == @x
      edges << [atx, aty]
      atx += 1
      aty -= 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]