-
Notifications
You must be signed in to change notification settings - Fork 4
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
fairer array sorting algorithm #1418
Conversation
…at fairly randomises the contents
nice one! good bit of algorithms. why not add a unit test to it to round it off? |
let currentIndex = array.length; | ||
|
||
// While there remain elements to shuffle... | ||
while (currentIndex != 0) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
as the last step, this will always swap the first element with itself. Which is not in itself a problem as it's a no-op, but it was interesting.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nice work, big improvement 👏
I have added a unit test, but it was tricky to know how to properly test this. I didn't want to add a test that ran too many cycles to find whether the spread was even or not so in the end I just wrote a test that calls the function 100 times and checks that the output array order is not the same as the input array order .... the input array size was 10, I guess in theory the test could fail if by chance the shuffle resulted in an array with the elements in the same order but I fugured that was incredibly unlikely enough to make this test valid. |
probably not worth going around the houses too much but if we're running it 100 times we should expect each number should be in each position at least a few times |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nice work 👏
What does this PR change?
Replace the existing shuffle array sort function with an algorithm that fairly randomises the contents. The new approach is based on the fisher-yates algothrithm (https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) a nice example of which you can see here: Fisher–Yates Shuffle
Current situation/background
@johnduffell rightly pointed out in a previous pr (#1415 (comment)) that the randomisation of the output array wasn't all that random;
results from his testing:
It shows a weighting more specifically to the first element in the array (ideally these figures ought to be as close to 10% each in order to show a fair distribution)
and with the new Fisher–Yates Shuffle algorithm we can see the results much more evenly distributed: