Backport #7935

Array#sample with random generator

Added by Marc-Andre Lafortune over 2 years ago. Updated over 2 years ago.

[ruby-core:52779]
Status:Closed
Priority:Normal
Assignee:Tomoyuki Chikanaga

Description

The Random generator method's rand is called with the wrong limit.

Kernel::rand(n) returns integer between 0 and n-1, but generator is called with (n-1).

For example:

require 'delegate'
[1, 2].sample(1, random: Random.new) # => [1], or [2]
[1, 2].sample(1, random: SimpleDelegator.new(Random.new)) # => [1], never [2]

test_random_ulong_limited

Associated revisions

Revision 39466
Added by Nobuyoshi Nakada over 2 years ago

random.c: increase limit for generic rand

  • random.c (rb_random_ulong_limited): limit is inclusive, but generic rand method should return a number less than it, so increase for the difference. [Bug #7935]

Revision 39470
Added by Nobuyoshi Nakada over 2 years ago

test_array.rb: fix test for r39466

  • test/ruby/test_array.rb (test_sample_random): remove adjustment for the bug fixed by r39466. [Bug #7935]

Revision 39675
Added by Tomoyuki Chikanaga over 2 years ago

merge revision(s) 39466,39470: [Backport #7935]

* random.c (rb_random_ulong_limited): limit is inclusive, but generic
  rand method should return a number less than it, so increase for the
  difference.   [Bug #7935]

* test/ruby/test_array.rb (test_sample_random): remove adjustment for
  the bug fixed by r39466.   [Bug #7935]

History

#1 Updated by Nobuyoshi Nakada over 2 years ago

  • Status changed from Open to Closed
  • % Done changed from 0 to 100

This issue was solved with changeset r39466.
Marc-Andre, thank you for reporting this issue.
Your contribution to Ruby is greatly appreciated.
May Ruby be with you.


random.c: increase limit for generic rand

  • random.c (rb_random_ulong_limited): limit is inclusive, but generic rand method should return a number less than it, so increase for the difference. [Bug #7935]

#2 Updated by Nobuyoshi Nakada over 2 years ago

  • Tracker changed from Bug to Backport
  • Project changed from Ruby trunk to Backport200
  • Category deleted (core)
  • Status changed from Closed to Assigned
  • Assignee set to Yusuke Endoh
  • Target version deleted (next minor)

#3 Updated by Tomoyuki Chikanaga over 2 years ago

  • Assignee changed from Yusuke Endoh to Tomoyuki Chikanaga

#4 Updated by Tomoyuki Chikanaga over 2 years ago

  • Status changed from Assigned to Closed

This issue was solved with changeset r39675.
Marc-Andre, thank you for reporting this issue.
Your contribution to Ruby is greatly appreciated.
May Ruby be with you.


merge revision(s) 39466,39470: [Backport #7935]

* random.c (rb_random_ulong_limited): limit is inclusive, but generic
  rand method should return a number less than it, so increase for the
  difference.   [Bug #7935]

* test/ruby/test_array.rb (test_sample_random): remove adjustment for
  the bug fixed by r39466.   [Bug #7935]

Also available in: Atom PDF