Last active
December 4, 2021 16:08
-
-
Save vczb/c063fd20dc308dadc5466c2f663381c0 to your computer and use it in GitHub Desktop.
Sorting an Array in Random Order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| The above example, array.sort(), is not accurate, it will favor some numbers over the others. | |
| The most popular correct method, is called the Fisher Yates shuffle, and was introduced in data science as early as 1938! | |
| In JavaScript the method can be translated to this: | |
| */ | |
| const points = [40, 100, 1, 5, 25, 10]; | |
| for (let i = points.length -1; i > 0; i--) { | |
| let j = Math.floor(Math.random() * i) | |
| let k = points[i] | |
| points[i] = points[j] | |
| points[j] = k | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const points = [40, 100, 1, 5, 25, 10]; | |
| points.sort(function(a, b){return 0.5 - Math.random()}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment