Skip to content

Instantly share code, notes, and snippets.

@tompng
Created April 28, 2024 13:20
Show Gist options
  • Save tompng/285b35550122ae188a4a4256981d993e to your computer and use it in GitHub Desktop.
Save tompng/285b35550122ae188a4a4256981d993e to your computer and use it in GitHub Desktop.
require 'matrix'
module RegEqSolver
class RHS
alias ~ binding
public :~
end
[Integer, Float, Rational, Complex].each do |klass|
refine klass do
def ~
$rhs = self
RHS.new
end
end
end
refine Regexp do
def =~ binding
params = source.scan(/(-?[\d.]+)\(\?<([a-z]+)>\)/)
[params, binding, $rhs]
end
end
refine Kernel do
def solve(*param_bind_rhs)
bind = nil
params = param_bind_rhs.map do |ps,b|
bind ||= b
ps.map(&:last)
end.flatten.uniq
rhs = []
matrix = param_bind_rhs.map do |ps,_b,r|
rhs << r
v = [0] * params.size
ps.each do |p|
v[params.index(p.last)] = p.first.to_f
end
v
end
ans = Matrix[*matrix].lup.solve(rhs)
params.zip(ans).each do |p,a|
bind.local_variable_set(p, a)
end
end
end
end
using RegEqSolver
solve(
/2(?<x>)+3(?<y>)/ =~~~ 8,
/5(?<x>)+2(?<y>)/ =~~~ 9,
/8(?<y>)-3(?<z>)/ =~~~ 7
)
p(x:, y:, z:)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment