Project

General

Profile

Actions

Bug #21106

closed

The last iteration of the rb_ary_shuffle_bang function is useless

Added by usumerican (usumerican _) 21 days ago. Updated 21 days ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +PRISM [x86_64-darwin21]
[ruby-core:120857]

Description

The number of iterations in the Fischer-Yates shuffle is (N-1) times.
In the following verification code, rand function is called N times.

class R
  def rand(n)
    puts n
    return 0
  end
end

a = [1,2,3,4,5,6,7,8,9,10]
puts a.shuffle(random: R.new).join(",")

The while conditional expression in the rb_ary_shuffle_bang function can be changed from while(n) to while(n > 1).

https://github.com/ruby/ruby/blob/db02a6b3ab4cabbdf492c26dcb1929b4ef0370a1/array.c#L6704

Actions #1

Updated by nobu (Nobuyoshi Nakada) 21 days ago

  • Status changed from Open to Closed

Applied in changeset git|8dd0d63550c4da2ba7939f371f73825caa2e932e.


[Bug #21106] Remove the useless last iteration

When only one element remains, this simply swaps the first identical
element and has no actual effect.

Actions

Also available in: Atom PDF

Like0
Like1