OSDN Git Service

improved fractional_arithmetic generator
authorTomohiro Nishimura <tomohiro68@gmail.com>
Fri, 16 Apr 2010 02:54:23 +0000 (11:54 +0900)
committerTomohiro Nishimura <tomohiro68@gmail.com>
Fri, 16 Apr 2010 02:54:23 +0000 (11:54 +0900)
lib/mint/generator/fractional_arithmetic.rb

index 0bcbf94..d7095ed 100644 (file)
@@ -35,6 +35,40 @@ module Mint::Generator
     option :denominator_max, 100
 
     def expression
+      return two_term_expression if options[:term_number] == 2
+      some_term_expression
+    end
+
+    def two_term_expression
+      result = []
+      result << operand
+      result << (operator = options[:operators].sample)
+      an, ad = result.first.scan(/(\d+)\/(\d+)/).first.map(&:to_i)
+      begin
+        numerator   = numerator_part
+        denominator = denominator_part
+        res_numerator, res_denominator =
+          result_parts(
+            an, ad,
+            numerator, denominator,
+            operator
+          )
+      end while is_lowest_term?(res_numerator, res_denominator)
+      result << "(%s/%s)" % [numerator, denominator]
+      result.join(' ')
+    end
+
+    def result_parts(a, b, c, d, op)
+      lcm = b.lcm(d)
+      case op
+        when '+' then return [a*lcm + c*lcm, lcm]
+        when '-' then return [a*lcm - c*lcm, lcm]
+        when '*' then return [a * c, b * d]
+        when 'div' then return [a * d, b * c]
+      end
+    end
+
+    def some_term_expression
       result = []
       operator = ''
       options[:term_number].times do