kujibiki 0.1.4 → 0.2.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/lib/kujibiki/core_ext/array.rb +36 -27
- data/lib/kujibiki/version.rb +1 -1
- metadata +1 -1
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 5a00aa2d312cdb6a276739da7fd703594f1d6d77
|
4
|
+
data.tar.gz: ec1f679ddd807cb3d49af9e03dd1d9d80a7c2a16
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: d33baa2cce6c158200ca79930aaf358c879fe0ef68390f565ebb945479dd95c174031db0f81a5274bf8df37979f4867bf1bab2b5fa3abf3b918dca96164ebc43
|
7
|
+
data.tar.gz: 9981869ef4d582dc539828bd8be38c8ef285ef3221d7772b584dcd12370b94ce6d338562e084a553c2c85f2cb0c4220e24388fd24bc60a54ffc389b129282990
|
@@ -1,43 +1,52 @@
|
|
1
1
|
class Array
|
2
2
|
alias_method :_sample, :sample
|
3
3
|
def sample(n=nil, random: nil, weight: nil)
|
4
|
-
|
5
|
-
if n
|
6
|
-
if random
|
7
|
-
return _sample(n, random: random)
|
8
|
-
else
|
9
|
-
return _sample(n)
|
10
|
-
end
|
11
|
-
else
|
12
|
-
if random
|
13
|
-
return _sample(random: random)
|
14
|
-
else
|
15
|
-
return _sample
|
16
|
-
end
|
17
|
-
end
|
18
|
-
end
|
4
|
+
return call_original_sample(n, random: random) if (weight.nil? || self.size <= 1)
|
19
5
|
|
20
6
|
unless weight.select {|w| w > 0}.size >= self.size
|
21
7
|
raise ArgumentError, "weight size must be larger than or equal to sample number(#{self.size})"
|
22
8
|
end
|
23
9
|
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
10
|
+
begin
|
11
|
+
sum = weight.inject(0.0, :+)
|
12
|
+
normalized_hash = self.each_with_object({}).with_index do |(e, h), i|
|
13
|
+
h[e] = weight[i] / sum
|
14
|
+
end
|
15
|
+
|
16
|
+
pick_max = 1.0
|
17
|
+
sampled = n.times.map do
|
18
|
+
pick = random ? random.rand(0..pick_max) : rand(0..pick_max)
|
28
19
|
|
29
|
-
|
30
|
-
|
31
|
-
|
20
|
+
e, weight = normalized_hash.find do |e, weight|
|
21
|
+
(pick <= weight) || ((pick -= weight) && false)
|
22
|
+
end
|
32
23
|
|
33
|
-
|
34
|
-
|
24
|
+
pick_max -= weight
|
25
|
+
normalized_hash[e] = 0 and e
|
35
26
|
end
|
36
27
|
|
37
|
-
|
38
|
-
|
28
|
+
sampled.size > 1 ? sampled : sampled.first
|
29
|
+
rescue => e
|
30
|
+
warn([e.class, e.message, e.backtrace.join("\n")].join(' '))
|
31
|
+
return call_original_sample(n, random: random)
|
39
32
|
end
|
33
|
+
end
|
40
34
|
|
41
|
-
|
35
|
+
private
|
36
|
+
|
37
|
+
def call_original_sample(n=nil, random: nil)
|
38
|
+
if n
|
39
|
+
if random
|
40
|
+
_sample(n, random: random)
|
41
|
+
else
|
42
|
+
_sample(n)
|
43
|
+
end
|
44
|
+
else
|
45
|
+
if random
|
46
|
+
_sample(random: random)
|
47
|
+
else
|
48
|
+
_sample
|
49
|
+
end
|
50
|
+
end
|
42
51
|
end
|
43
52
|
end
|
data/lib/kujibiki/version.rb
CHANGED