JavaScript Random Shuffle Algorithm for Randomly Disrupting Array Order
- 2021-07-07 06:17:28
- OfStack
Suppose there is an array that looks like this:
var arr1 = ["a", "b", "c", "d"];
How to randomly disrupt the array order, that is, shuffle.
There is a simple random algorithm that is widely spread:
function RandomSort (a,b){ return (0.5 - Math.random()); }
It turns out that the above is not completely random.
There are too many such things on the Internet. Look at a high score answer on stackoverflow. The answer comes from github.
knuth-shuffle
The Fisher-Yates (aka Knuth) shuffle for Browser and Node.JS
Take a look at the algorithm mentioned above from the following 1. The code is as follows:
/*jshint -W054 */
(function (exports) {
'use strict';
// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
function shuffle(array) {
var currentIndex = array.length
, temporaryValue
, randomIndex
;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
exports.knuthShuffle = shuffle;
}('undefined' !== typeof exports && exports || 'undefined' !== typeof window && window || global));
The author recommends using browser writing:
(function () {
'use strict';
var a = [2,11,37,42]
, b
;
// The shuffle modifies the original array
// calling a.slice(0) creates a copy, which is assigned to b
b = window.knuthShuffle(a.slice(0));
console.log(b);
}());
Nodejs:
npm install -S knuth-shuffle
(function () {
'use strict';
var shuffle = require('knuth-shuffle').knuthShuffle
, a = [2,11,37,42]
, b
;
// The shuffle modifies the original array
// calling a.slice(0) creates a copy, which is assigned to b
b = shuffle(a.slice(0));
console.log(b);
}());
There are other variants from this algorithm, such as the following for loop. Don't say anything else.
/**
* Randomize array element order in-place.
* Using Durstenfeld shuffle algorithm.
*/
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
Use ES2015 (ES6)
Array.prototype.shuffle = function() {
let m = this.length, i;
while (m) {
i = (Math.random() * m--) >>> 0;
[this[m], this[i]] = [this[i], this[m]]
}
return this;
}
Use:
[1, 2, 3, 4, 5, 6, 7].shuffle();
It is found that there are a lot of random algorithms for Chinese search, but whether they are completely random, efficiency and compatibility need to be studied. It is suggested that if there is a need to randomly scramble array elements, the above one can be used.