Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

squint/core Shuffle function suggestions #513

Closed
kigiri opened this issue Apr 20, 2024 · 2 comments
Closed

squint/core Shuffle function suggestions #513

kigiri opened this issue Apr 20, 2024 · 2 comments

Comments

@kigiri
Copy link
Contributor

kigiri commented Apr 20, 2024

squint/src/squint/core.js

Lines 1851 to 1855 in 6d6e3fc

export function shuffle(coll) {
return [...coll].sort(function (_a, _b) {
return Math.random() - 0.5;
});
}

This is not a good way to shuffle, distribution is biased, and it's not efficient.

function shuffle(coll) {
  const result = [...coll]
  let left = coll.length
  while (left) {
    const i = Math.floor(Math.random() * left--)
    const tmp = result[left]
    result[left] = result[i]
    result[i] = tmp
  }

  return result
}

Here an example of the distribution in chrome:
image

You can read more about why this isn't a recommanded method here:
https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling

And here, clicking on the solution for straitforward examples: https://javascript.info/task/shuffle

@borkdude
Copy link
Member

Thanks!

@borkdude
Copy link
Member

The source code you list after the squint link, is that a recommendation of how to do it, or not?
It seems fairly close to how goog.array is doing it: https://github.com/google/closure-library/blob/master/closure/goog/array/array.js#L1741
If so, PR welcome

kigiri added a commit to kigiri/squint that referenced this issue Apr 30, 2024
kigiri added a commit to kigiri/squint that referenced this issue Apr 30, 2024
kigiri added a commit to kigiri/squint that referenced this issue Apr 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants