function shuffle(array) {let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.while (currentIndex != 0) {
// Pick a remaining element.randomIndex = Math.floor(Math.random() * currentIndex);currentIndex--;
// And swap it with the current element.[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];}
return array;}
// Used like sovar arr = [2, 11, 37, 42];shuffle(arr);console.log(arr);
function shuffle(array) {var random = array.map(Math.random);array.sort(function(a, b) {return random[array.indexOf(a)] - random[array.indexOf(b)];});}
var arr = ['apple','cat','Adam','123','Zorro','petunia'];var n = arr.length; var tempArr = [];
for ( var i = 0; i < n-1; i++ ) {
// The following line removes one random element from arr// and pushes it onto tempArrtempArr.push(arr.splice(Math.floor(Math.random()*arr.length),1)[0]);}
// Push the remaining item onto tempArrtempArr.push(arr[0]);arr=tempArr;
function swap(arr, i, j) {// swaps two elements of an array in placevar temp = arr[i];arr[i] = arr[j];arr[j] = temp;}function randInt(max) {// returns random integer between 0 and max-1 inclusive.return Math.floor(Math.random()*max);}function shuffle(arr) {// For each slot in the array (starting at the end),// pick an element randomly from the unplaced elements and// place it in the slot, exchanging places with the// element in the slot.for(var slot = arr.length - 1; slot > 0; slot--){var element = randInt(slot+1);swap(arr, element, slot);}}
var shuffledArray = function(inpArr){//inpArr - is input arrayvar arrRand = []; //this will give shuffled arrayvar arrTempInd = []; // to store shuffled indexesvar max = inpArr.length;var min = 0;var tempInd;var i = 0;
do{//generate random index between rangetempInd = Math.floor(Math.random() * (max - min));//check if index is already available in array to avoid repetitionif(arrTempInd.indexOf(tempInd)<0){//push character at random indexarrRand[i] = inpArr[tempInd];//push random indexesarrTempInd.push(tempInd);i++;}}// check if random array length is equal to input array lengthwhile(arrTempInd.length < max){return arrRand; // this will return shuffled Array}};
// Both work. The second one wouldn't have worked as the one abovevar randomsquares = [1, 2, 3, 4, 5, 6, 7].reduce(shuffle, []).map(n => n*n);var randomsquares = [].reduce(shuffle, []).map(n => n*n);
让我们将shuffle定义为:
var shuffle = (rand, one, i, orig) => {if (i !== 1) return rand; // Randomize it only once (arr.length > 1)
// You could use here other random algorithm if you wantedfor (let i = orig.length; i; i--) {let j = Math.floor(Math.random() * i);[orig[i - 1], orig[j]] = [orig[j], orig[i - 1]];}
return orig;}
您可以在操作在JSFiddle中或此处看到它:
var shuffle = (all, one, i, orig) => {if (i !== 1) return all;
// You could use here other random algorithm herefor (let i = orig.length; i; i--) {let j = Math.floor(Math.random() * i);[orig[i - 1], orig[j]] = [orig[j], orig[i - 1]];}
return orig;}
for (var i = 0; i < 5; i++) {var randomarray = [1, 2, 3, 4, 5, 6, 7].reduce(shuffle, []);console.log(JSON.stringify(randomarray));}
function shuffleArray(array) {// Create a new array with the length of the given array in the parametersconst newArray = array.map(() => null);
// Create a new array where each index contain the index valueconst arrayReference = array.map((item, index) => index);
// Iterate on the array given in the parametersarray.forEach(randomize);
return newArray;
function randomize(item) {const randomIndex = getRandomIndex();
// Replace the value in the new arraynewArray[arrayReference[randomIndex]] = item;
// Remove in the array reference the index usedarrayReference.splice(randomIndex,1);}
// Return a number between 0 and current array reference lengthfunction getRandomIndex() {const min = 0;const max = arrayReference.length;return Math.floor(Math.random() * (max - min)) + min;}}
console.log(shuffleArray([10,20,30,40,50,60,70,80,90,100]));
/*** Returns a new array whose contents are a shuffled copy of the original array.* @param {Array} The items to shuffle.* https://stackoverflow.com/a/2450976/1673761* https://stackoverflow.com/a/44071316/1673761*/const shuffle = (array) => {let currentIndex = array.length;let temporaryValue;let randomIndex;const newArray = array.slice();// While there remains elements to shuffle...while (currentIndex) {randomIndex = Math.floor(Math.random() * currentIndex);currentIndex -= 1;// Swap it with the current element.temporaryValue = newArray[currentIndex];newArray[currentIndex] = newArray[randomIndex];newArray[randomIndex] = temporaryValue;}return newArray;};
var shuffle = a => a.length ? a.splice(~~(Math.random()*a.length),1).concat(shuffle(a)): a;
console.log(JSON.stringify(shuffle([0,1,2,3,4,5,6,7,8,9])));
function testShuffleArrayFun(getShuffledArrayFun){const arr = [0,1,2,3,4,5,6,7,8,9]
var countArr = arr.map(el=>{return arr.map(el=> 0)}) // For each possible position in the shuffledArr and for// each possible value, we'll create a counter.const t0 = performance.now()const n = 1000000for (var i=0 ; i<n ; i++){// We'll call getShuffledArrayFun n times.// And for each iteration, we'll increment the counter.var shuffledArr = getShuffledArrayFun(arr)shuffledArr.forEach((value,key)=>{countArr[key][value]++})}const t1 = performance.now()console.log(`Count Values in position`)console.table(countArr)
const frequencyArr = countArr.map( positionArr => (positionArr.map(count => count/n)))
console.log("Frequency of value in position")console.table(frequencyArr)console.log(`total time: ${t1-t0}`)}
var d = [1,2,3,4,5,6,7,8,9,10];
function shuffle(a) {var x, t, r = new Uint32Array(1);for (var i = 0, c = a.length - 1, m = a.length; i < c; i++, m--) {crypto.getRandomValues(r);x = Math.floor(r / 65536 / 65536 * m) + i;t = a [i], a [i] = a [x], a [x] = t;}
return a;}
console.log(shuffle(d));
function shuffle(array) {var result = [], source = array.concat([]);
while (source.length) {let index = Math.floor(Math.random() * source.length);result.push(source[index]);source.splice(index, 1);}
return result;}
function shuffle(array) {var result = [], source = array.concat([]);
while (source.length) {let index = Math.floor(Math.random() * source.length);result.push(source.splice(index, 1)[0]);}
return result;}
// Create a places array which holds the index for each item in the// passed in array.//// Then return a new array by randomly selecting items from the// passed in array by referencing the places array item. Removing that// places item each time though.function shuffle(array) {let places = array.map((item, index) => index);return array.map((item, index, array) => {const random_index = Math.floor(Math.random() * places.length);const places_value = places[random_index];places.splice(random_index, 1);return array[places_value];})}
var ia= [1,2,3];var it= 1000;var f = (a,x,i)=>{a.splice(Math.floor(Math.random()*(i+1)),0,x);return a};var a = new Array(it).fill(ia).map(x=>x.reduce(f,[]));var r = new Array(ia.length).fill(0).map((x,i)=>a.reduce((i2,x2)=>x2[i]+i2,0)/it)
console.log("These values should be quite equal:",r);
const array = [1, 2, 3, 4];
// Based on the value returned by Math.Random,// the decision is arbitrarily made whether to return 1 : -1
const shuffeled = array.sort(() => {const randomTrueOrFalse = Math.random() > 0.5;return randomTrueOrFalse ? 1 : -1});
console.log(shuffeled);
社区说arr.sort((a, b) => 0.5 - Math.random())不是100%随机的! 是的!我测试并推荐不要使用这种方法!
let arr = [1, 2, 3, 4, 5, 6]arr.sort((a, b) => 0.5 - Math.random());
但我不确定。所以我写了一些代码来测试!…你也可以试试!如果你足够感兴趣!
let data_base = [];for (let i = 1; i <= 100; i++) { // push 100 time new rendom arr to data_base!data_base.push([1, 2, 3, 4, 5, 6].sort((a, b) => {return Math.random() - 0.5; // used community banned method! :-)}));} // console.log(data_base); // if you want to see data!let analysis = {};for (let i = 1; i <= 6; i++) {analysis[i] = Array(6).fill(0);}for (let num = 0; num < 6; num++) {for (let i = 1; i <= 100; i++) {let plus = data_base[i - 1][num];analysis[`${num + 1}`][plus-1]++;}}console.log(analysis); // analysed result
// Original arraylet array = ['a', 'b', 'c', 'd'];
// Create a copy of the original array to be randomizedlet shuffle = [...array];
// Defining function returning random value from i to Nconst getRandomValue = (i, N) => Math.floor(Math.random() * (N - i) + i);
// Shuffle a pair of two elements at random position jshuffle.forEach( (elem, i, arr, j = getRandomValue(i, arr.length)) => [arr[i], arr[j]] = [arr[j], arr[i]] );
console.log(shuffle);// ['d', 'a', 'b', 'c']
function shuffle (t){ let last = t.lengthlet nwhile (last > 0){ n = rand(last)swap(t, n, --last)}}
const rand = n =>Math.floor(Math.random() * n)
function swap (t, i, j){ let q = t[i]t[i] = t[j]t[j] = qreturn t}
const size = 1e6const bigarray = Array.from(Array(size), (_,i) => i)console.time("shuffle in place")shuffle(bigarray)console.timeEnd("shuffle in place")document.body.textContent = JSON.stringify(bigarray, null, 2)
body::before {content: "1 million elements in place";font-weight: bold;display: block;}