From dfefec37c7547d3da271ea3af6fec415e1fb6faa Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Fri, 13 Dec 2024 13:49:28 -0800 Subject: [PATCH] [2024][ruby][13.x] use matrices --- 2024/ruby/day_13.rb | 31 +++++++++---------------------- 1 file changed, 9 insertions(+), 22 deletions(-) diff --git a/2024/ruby/day_13.rb b/2024/ruby/day_13.rb index 1d79604..3416982 100644 --- a/2024/ruby/day_13.rb +++ b/2024/ruby/day_13.rb @@ -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