Skip to content

fix: Array#shuffle(!) result distribution - #6227

Merged
matz merged 1 commit into
mruby:masterfrom
leviongit:array/shuffle_b
Apr 4, 2024
Merged

fix: Array#shuffle(!) result distribution#6227
matz merged 1 commit into
mruby:masterfrom
leviongit:array/shuffle_b

Conversation

@leviongit

Copy link
Copy Markdown
Contributor

previously the shuffle algorithm would leave the first element untouched about 1/3rd of the time

@leviongit
leviongit requested a review from matz as a code owner April 4, 2024 18:38
@Ferociousfeind

Copy link
Copy Markdown

I can mathematically confirm these changes are correct- there are "n!" ways to order a list of "n" elements, however the original functionality would randomly pick one of "n^n" elements.

This necessarily would produce lopsided behavior, as n^n is not an integer multiple of n!, except in the case where n=0, 1, or 2 (where n^n is (effectively) 0, 1 and 4 respectively, and n! is (effectively) 0, 1 and 2 respectively), in all other cases, the "n is never divisible by n-1" rule comes into play and makes some permutations appear more often than others.

This appears to manifest as the 0th element of an array moving around significantly less often than other elements, which this PR fixes.

@matz
matz merged commit 47642f7 into mruby:master Apr 4, 2024
@matz

matz commented Apr 4, 2024

Copy link
Copy Markdown
Member

Thank you.

@leviongit
leviongit deleted the array/shuffle_b branch January 26, 2025 03:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants