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

sort function is required to return a stable value #9

Open
normanr opened this issue Dec 4, 2019 · 0 comments
Open

sort function is required to return a stable value #9

normanr opened this issue Dec 4, 2019 · 0 comments

Comments

@normanr
Copy link

normanr commented Dec 4, 2019

The function passed to sort is supposed to return the same value when given a specific pair of elements a and b as its two arguments (ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description)

prefix = prefix.split('').sort(function(){return 0.5-Math.random()}).join('')

does not meet this requirement. https://medium.com/@nitinpatel_20236/how-to-shuffle-correctly-shuffle-an-array-in-javascript-15ea3f84bfb has some commentary on why this is bad.

does not meet this requirement. https://medium.com/@nitinpatel_20236/how-to-shuffle-correctly-shuffle-an-array-in-javascript-15ea3f84bfb has some commentary on why this is bad.

There are various ways to do it correctly, either Fisher–Yates or the "assign a random number to each element" method. The former is more efficient (and doesn't have a problem if the function returns the same value twice), but the latter is shorter to implement in javascript (and the number of input elements so low that it practically doesn't matter):

prefix = prefix.split('').map(x=>[Math.random(),x]).sort().map(x=>x[1]).join('');

or non ES6 syntax:

prefix = prefix.split('').map(function(x){return[Math.random(),x]}).sort().map(function(x){return x[1]}).join('')

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

1 participant