Skip to content

Commit 36e4b03

Browse files
author
Peter de Ruijter
committed
Adds race condition with all weights 0.
1 parent 6ca3dca commit 36e4b03

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

lib/array.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
class Array
22
def weighted_sample(weights=nil)
3-
weights ||= Array.new(length, 1.0)
4-
3+
weights = Array.new(length, 1.0) if weights.nil? || weights.sum == 0
54
total = weights.sum
65

76
# The total sum of weights is multiplied by a random number

spec/array_spec.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@
4141
before { Kernel.stub(:rand) { 1 } }
4242
subject { array.weighted_sample([0, 0, 0, 0]) }
4343
it { should eq 4 }
44+
context "random 0" do
45+
before { Kernel.stub(:rand) { 0 } }
46+
it { should eq 1 }
47+
end
4448
end
4549
end
4650
end

0 commit comments

Comments
 (0)