[2024][ruby][13.x] use matrices

main
Alpha Chen 1 week ago
parent 9916480f1c
commit dfefec37c7
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -1,11 +1,4 @@
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "z3"
end
require "z3"
require "matrix"
input = DATA.read
@ -13,16 +6,10 @@ machines = input.split("\n\n")
.map {|machine| machine.scan(/\d+/).map(&:to_i).each_slice(2).to_a }
def wins(machine)
a = Z3.Int("a")
b = Z3.Int("b")
solver = Z3::Solver.new
machine.transpose.each do |a_, b_, c|
solver.assert a*a_ + b*b_ == c
end
if solver.satisfiable?
model = solver.model
[a, b].map { model[_1].to_i }
*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
@ -37,16 +24,16 @@ pp machines
__END__
Button A: X+94, Y+34
Button B: X+22, Y+67
Prize: X=8400, Y=5400
Prize: X=10000000008400, Y=10000000005400
Button A: X+26, Y+66
Button B: X+67, Y+21
Prize: X=12748, Y=12176
Prize: X=10000000012748, Y=10000000012176
Button A: X+17, Y+86
Button B: X+84, Y+37
Prize: X=7870, Y=6450
Prize: X=10000000007870, Y=10000000006450
Button A: X+69, Y+23
Button B: X+27, Y+71
Prize: X=18641, Y=10279
Prize: X=10000000018641, Y=10000000010279

Loading…
Cancel
Save