1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require "matrix"

input = DATA.read

machines = input.split("\n\n")
  .map {|machine| machine.scan(/\d+/).map(&:to_i).each_slice(2).to_a }

def wins(machine)
  *ab, c = machine
  a, b = (Matrix.columns(ab).inverse * Matrix.column_vector(c)).to_a.flatten
  if [a, b].all? { _1.denominator == 1 }
    [a, b].map(&:to_i)
  else
    nil
  end
end

pp machines.map { wins(_1) }.compact.sum { 3 * _1 + _2 }

pp machines
  .map {|a,b,c| [a,b,c.map { _1 + 10_000_000_000_000 }] }
  .map { wins(_1) }.compact.sum { 3 * _1 + _2 }

__END__