Skip to content

Instantly share code, notes, and snippets.

@udzura
Created November 12, 2023 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save udzura/8b0f622c2993c635b84e27156a85697c to your computer and use it in GitHub Desktop.
Save udzura/8b0f622c2993c635b84e27156a85697c to your computer and use it in GitHub Desktop.
MATCH_EQ = /(-?)([0-9]*)x(\+|-)([0-9]*)y=(-?)([0-9]+)/
def parse_equation(eq)
unless eq.match(MATCH_EQ)
raise "unsupported"
end
x = 0
y = 0
xsig = $1
xcoeff = $2
ysig = $3
ycoeff = $4
rhssig = $5
rhs = $6.to_i
if xcoeff.empty?
xcoeff = 1
end
if xsig.empty?
x = xcoeff.to_i
else
x = -xcoeff.to_i
end
if ycoeff.empty?
ycoeff = 1
end
if ysig == '+'
y = ycoeff.to_i
else
y = -ycoeff.to_i
end
if rhssig.empty?
rhssig = 1
else
rhssig = -1
end
return [x, y, rhssig*rhs]
end
puts "first equation?"
x, y, rhs = parse_equation(gets)
p [x, y, rhs]
puts "second equation?"
x2, y2, rhs2 = parse_equation(gets)
p [x2, y2, rhs2]
require 'matrix'
mat_A = Matrix[
[ x, y],
[x2, y2],
]
mat_B = Matrix[
[rhs],
[rhs2]
]
begin
mat_A_dash = mat_A.inverse
rescue ExceptionForMatrix::ErrNotRegular => e
raise "その連立方程式は解けません"
end
ans = mat_A_dash * mat_B
puts <<EOS
x = #{ans[0, 0]}
y = #{ans[1, 0]}
EOS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment