Backport #7935

Array#sample with random generator

Added by Marc-Andre Lafortune about 1 year ago. Updated about 1 year ago.

[ruby-core:52779]
Status:Closed
Priority:High
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]

testrandomulong_limited

Associated revisions

Revision 39675
Added by Tomoyuki Chikanaga about 1 year 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 about 1 year 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 (rbrandomulong_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 about 1 year 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 about 1 year ago

  • Assignee changed from Yusuke Endoh to Tomoyuki Chikanaga

#4 Updated by Tomoyuki Chikanaga about 1 year 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