euler/ruby/euler033.rb

57 lines
1.2 KiB
Ruby
Raw Normal View History

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
2014-04-25 23:59:14 +00:00
end
end
pairs
2014-04-25 23:59:14 +00:00
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)
2014-04-25 23:59:14 +00:00
end
solutions
end
def reduce_fraction(numerator, denominator)
until (gcd = gcd(numerator, denominator)) == 1
numerator /= gcd
denominator /= gcd
end
[numerator, denominator]
2014-04-25 23:59:14 +00:00
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