OSDN Git Service

move parenthesis into create_complex_number
[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   # [_term_number_]
10   #   生成する式の項数を1以上の整数で指定します。
11   # [_operators_]
12   #   使用可能な演算子を指定します。
13   #   *, / の2種類から使用したいものを配列で指定します。
14   # [_min_]
15   #   生成する式の各項の最小値を0以上の整数で指定します。
16   # [_max_]
17   #   生成する式の各項の最大値を0以上の整数で指定します。
18   #   _min_ よりも小さい値を指定することは出来ません。
19   # [_fractional_mode_]
20   #   真を指定すると分数形式の項を生成します。
21   #
22   class ComplexNumberArithmetic < Arithmetic
23
24     private
25
26     option :min,             1
27     option :max,             9
28     option :fractional_mode, false
29     option :operators,       %w[ * / ]
30
31     def setup
32       if options[:fractional_mode]
33         @options[:operators] = %w[ + - ]
34       end
35     end
36
37     def operand
38       result =
39         if options[:fractional_mode]
40           create_fractional_complex_number
41         else
42           create_complex_number
43         end
44       return "#{result}^2" if options[:term_number] == 1
45       return conjugate_complex(last_operand) if last_operator == '/'
46       result
47     end
48
49     def create_complex_number
50       real_part = create_integer(options[:min], options[:max], false)
51       imaginary_part =  create_integer(options[:min], options[:max], false)
52       return (2 + rand(8)).to_s if [real_part, imaginary_part].include? 0
53       operator =  %w[ + - ].sample
54       "(#{real_part} #{operator} #{imaginary_part.to_s.sub('1', '')}%i)"
55     end
56
57     def create_fractional_complex_number
58       numerator_part = 1 + rand(9)
59       denominator_part = create_complex_number
60       "#{numerator_part} / #{denominator_part}"
61     end
62
63     def conjugate_complex(expression)
64       a, op, b = *expression.split
65       op = op == '+' ? '-' : '+'
66       "#{a} #{op} #{b}"
67     end
68   end
69 end
70