57 lines
1.2 KiB
Ruby
57 lines
1.2 KiB
Ruby
|
def gcd(a, b)
|
||
|
b == 0 ? a : gcd(b, a % b)
|
||
|
end
|
||
|
|
||
|
def generate_fractional_pairs
|
||
|
pairs = []
|
||
|
(10..99).each do |i|
|
||
|
(10..99).each do |j|
|
||
|
pairs << [i,j] if i < j
|
||
|
end
|
||
|
end
|
||
|
pairs
|
||
|
end
|
||
|
|
||
|
def check_weird_cancellations
|
||
|
solutions = []
|
||
|
fractions = generate_fractional_pairs
|
||
|
|
||
|
fractions.each do |fraction|
|
||
|
next if fraction.first % 10 == 0
|
||
|
num = fraction.first.to_s
|
||
|
den = fraction.last.to_s
|
||
|
|
||
|
if (num.include?(den[0]))
|
||
|
digit = num[num.index(den[0])]
|
||
|
new_num = num.delete(digit)
|
||
|
new_den = den.delete(digit)
|
||
|
elsif (num.include?(den[1]))
|
||
|
digit = num[num.index(den[1])]
|
||
|
new_num = num.delete(digit)
|
||
|
new_den = den.delete(digit)
|
||
|
end
|
||
|
|
||
|
solutions << [fraction.first, fraction.last] if (num.to_f / den.to_f) == (new_num.to_f / new_den.to_f)
|
||
|
|
||
|
end
|
||
|
solutions
|
||
|
end
|
||
|
|
||
|
def reduce_fraction(numerator, denominator)
|
||
|
until (gcd = gcd(numerator, denominator)) == 1
|
||
|
numerator /= gcd
|
||
|
denominator /= gcd
|
||
|
end
|
||
|
[numerator, denominator]
|
||
|
end
|
||
|
|
||
|
def multiply_fractions(fractions)
|
||
|
numerators = 1
|
||
|
denominators = 1
|
||
|
fractions.each do |fraction|
|
||
|
numerators *= fraction.first
|
||
|
denominators *= fraction.last
|
||
|
end
|
||
|
reduce_fraction(numerators, denominators)
|
||
|
end
|