OSDN Git Service

313320c82b4d6e77f550feb8347bee31d3f68fea
[mint/mint-lib.git] / lib / mint / generator / complex_number_arithmetic.rb
1 # -*- coding: nil -*-
2
3 module Mint::Generator
4
5   #
6   # 複素数の問題を生成するジェネレータ
7   #
8   # オプション ::
9   #               以下のオプションが使用出来る
10   #               [_term_number_] 生成する項の数 (ex. 2)
11   #               [_operators_] 使用する演算子 (ex. %w[ * / ])
12   #               [_min_] 各項の最小値 (ex. 0)
13   #               [_max_] 各項の最大値 (ex. 100)
14   #               [_fractional_mode_] 真なら分数形式の項を生成する (ex. false)
15   #
16   class ComplexNumberArithmetic < Arithmetic
17
18     private
19
20     def generate_problem
21       defaults = {
22         :min => 1, :max => 9,
23         :fractional_mode => false,
24         :operators => %w[ * / ]
25       }
26       if options[:fractional_mode]
27         @options[:operators] = %w[ + - ]
28       end
29       do_generate(defaults)
30     end
31
32     def operand
33       result =
34         if options[:fractional_mode]
35           create_fractional_complex_number
36         else
37           "(#{create_complex_number})"
38         end
39       return "#{result}^2"if options[:term_number] == 1
40       if last_operator == '/'
41         return conjugate_complex(last_operand)
42       end
43       result
44     end
45
46     def create_complex_number
47       real_part = create_integer(options[:min], options[:max], false)
48       imaginary_part =  create_integer(options[:min], options[:max], false)
49       return (2 + rand(8)).to_s if [real_part, imaginary_part].include? 0
50       operator =  %w[ + - ].sample
51       "#{real_part} #{operator} #{imaginary_part.to_s.sub('1', '')}%i"
52     end
53
54     def create_fractional_complex_number
55       numerator_part = 1 + rand(9)
56       denominator_part = create_complex_number
57       "#{numerator_part} / (#{denominator_part})"
58     end
59
60     def conjugate_complex(expression)
61       a, op, b = *expression.split
62       op = op == '+' ? '-' : '+'
63       "#{a} #{op} #{b}"
64     end
65   end
66 end
67