OSDN Git Service

expansion generator supports multiple variable
[mint/mint-lib.git] / lib / mint / generator / utilities / common_utils.rb
1 module Mint::Generator
2
3   module Utilities
4
5     def create_integer(min, max, minus)
6       min, max = [min, max].map {|i| i < 0 ? -i : i }.sort
7       begin
8         n = rand(max+1)
9       end until min <= n
10       (n * sign(minus))
11     end
12
13     def sign(minus)
14       if minus
15         rand(2) == 0 ? 1 : -1
16       else
17         1
18       end
19     end
20
21     def factor(options, target = 'factor')
22       create_integer(options[:"#{target}_min"], options[:"#{target}_max"], options[:"#{target}_minus"])
23     end
24
25     def single(a, b, v = 'x')
26       return x if b == 0
27       v = Array(v)
28       x, y = v.values_at(0, 1)
29       ("(%d%s + %d%s)" % [a, x, b, y]).
30         gsub(%r!\+ -!, '- ').
31         gsub(/1(?!\d)(#{v.join('|')})/, '\1')
32     end
33
34     def min_max_order(options, targets)
35       targets.each do |type|
36         min = options[:"#{type}_min"]
37         if min > options[:"#{type}_max"]
38           options[:"#{type}_max"] = min
39         end
40       end
41       options
42     end
43   end
44 end
45
46 class Array
47   unless public_method_defined?(:sample)
48     def sample(n = nil)
49       if n
50         shuffle.slice(0..(n-1))
51       else
52         choice
53       end
54     end
55   end
56 end