如何随机化(shuffle)一个JavaScript数组?

时间:2010-03-15 22:37:12

标签: javascript arrays shuffle

我有一个这样的数组:

var arr1 = ["a", "b", "c", "d"];

我如何随机化/随机播放?

63 个答案:

答案 0 :(得分:1283)

事实上无偏见的随机播放算法是Fisher-Yates(又名Knuth)Shuffle。

请参阅https://github.com/coolaj86/knuth-shuffle

您可以看到great visualization here(以及原始帖子linked to this

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;
}

// Used like so
var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);

使用了更多信息about the algorithm

答案 1 :(得分:593)

以下是Durstenfeld shuffle的JavaScript实现,这是Fisher-Yates的计算机优化版本:

/**
 * 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;
    }
}

Fisher-Yates算法的工作原理是为每个原始数组元素选择一个随机元素,然后将其从下一个绘制中排除。就像从一副牌中随机挑选一样。

这种排除是以巧妙的方式完成的(由Durstenfeld发明供计算机使用),方法是将拾取的元素与当前元素交换,然后从剩余部分中挑选下一个随机元素。为了获得最佳效率,循环向后运行以便随机选择被简化(它总是从0开始),并且它跳过最后一个元素,因为不再有其他选择。

该算法的运行时间为O(n)。请注意,shuffle是就地完成的。因此,如果您不想修改原始数组,请先使用.slice(0)制作副本。

更新至ES6 / ECMAScript 2015

新的ES6允许我们一次分配两个变量。当我们想要交换两个变量的值时,这尤其方便,因为我们可以在一行代码中完成。这是使用此功能的相同功能的缩写形式。

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

答案 2 :(得分:105)

[社区编辑:这个答案不正确;看评论。它留在这里供将来参考,因为这个想法并不罕见。]

[1,2,3,4,5,6].sort(function() {
  return .5 - Math.random();
});

答案 3 :(得分:69)

可以(或应该)将它用作Array的原型:来自ChristopheR:

Array.prototype.shuffle = function() {
  var i = this.length, j, temp;
  if ( i == 0 ) return this;
  while ( --i ) {
     j = Math.floor( Math.random() * ( i + 1 ) );
     temp = this[i];
     this[i] = this[j];
     this[j] = temp;
  }
  return this;
}

答案 4 :(得分:58)

使用underscore.js库。方法_.shuffle()对于这种情况很好。 以下是该方法的示例:

var _ = require("underscore");

var arr = [1,2,3,4,5,6];
// Testing _.shuffle
var testShuffle = function () {
  var indexOne = 0;
    var stObj = {
      '0': 0,
      '1': 1,
      '2': 2,
      '3': 3,
      '4': 4,
      '5': 5
    };
    for (var i = 0; i < 1000; i++) {
      arr = _.shuffle(arr);
      indexOne = _.indexOf(arr, 1);
      stObj[indexOne] ++;
    }
    console.log(stObj);
};
testShuffle();

答案 5 :(得分:47)

您可以使用地图和排序轻松完成:

let unshuffled = ['hello', 'a', 't', 'q', 1, 2, 3, {cats: true}]

let shuffled = unshuffled
  .map((a) => ({sort: Math.random(), value: a}))
  .sort((a, b) => a.sort - b.sort)
  .map((a) => a.value)
  1. 我们将数组中的每个元素放在一个对象中,然后给它一个随机排序键
  2. 我们使用随机密钥
  3. 排序
  4. 我们取消映射以获取原始对象
  5. 您可以随机播放多态数组,并且排序与Math.random一样随机,这对于大多数用途来说已经足够了。

    由于元素是针对每次迭代不重新生成的一致键进行排序的,并且每个比较都来自同一个分布,因此Math.random分布中的任何非随机性都会被取消。

答案 6 :(得分:47)

NEW!

更短&amp;可能*更快的Fisher-Yates shuffle算法

  1. 它使用while ---
  2. 按位到楼层(最多10位十进制数字(32位))
  3. 删除了不必要的关闭&amp;其他的东西

  4. function fy(a,b,c,d){//array,placeholder,placeholder,placeholder
     c=a.length;while(c)b=Math.random()*(--c+1)|0,d=a[c],a[c]=a[b],a[b]=d
    }
    

    脚本大小(使用fy作为函数名称):90bytes

    <强>样本 http://jsfiddle.net/vvpoma8w/

    *可能在除chrome之外的所有浏览器上更快。

    如果您有任何问题,请询问。

    修改

    是的,它更快

    效果 http://jsperf.com/fyshuffle

    使用最高投票功能。

    修改 有一个计算超出(不需要--c + 1)没有人注意到

    更短(4字节)和更快(测试它!)。

    function fy(a,b,c,d){//array,placeholder,placeholder,placeholder
     c=a.length;while(c)b=Math.random()*c--|0,d=a[c],a[c]=a[b],a[b]=d
    }
    

    在其他地方缓存var rnd=Math.random,然后使用rnd()也会略微提高大数组的性能。

    http://jsfiddle.net/vvpoma8w/2/

    可读版本(使用原始版本。这比较慢,vars没用,比如闭包&amp;“;”,代码本身也更短......也许读这个{{3你不能在像上面这样的javascript minifiers中压缩下面的代码。)

    function fisherYates( array ){
     var count = array.length,
         randomnumber,
         temp;
     while( count ){
      randomnumber = Math.random() * count-- | 0;
      temp = array[count];
      array[count] = array[randomnumber];
      array[randomnumber] = temp
     }
    }
    

答案 7 :(得分:32)

小型阵列的一种非常简单的方法就是这样:

const someArray = [1, 2, 3, 4, 5];

someArray.sort(() => Math.random() - 0.5);

它可能效率不高,但对于小型阵列,这种方法效果很好。这是一个示例,因此您可以看到它是否随机(或不是),以及它是否适合您的用例。

&#13;
&#13;
const resultsEl = document.querySelector('#results');
const buttonEl = document.querySelector('#trigger');

const generateArrayAndRandomize = () => {
  const someArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  someArray.sort(() => Math.random() - 0.5);
  return someArray;
};

const renderResultsToDom = (results, el) => {
  el.innerHTML = results.join(' ');
};

buttonEl.addEventListener('click', () => renderResultsToDom(generateArrayAndRandomize(), resultsEl));
&#13;
<h1>Randomize!</h1>
<button id="trigger">Generate</button>
<p id="results">0 1 2 3 4 5 6 7 8 9</p>
&#13;
&#13;
&#13;

答案 8 :(得分:22)

添加到@Laurens Holsts回答。这是50%压缩。

function shuffleArray(d) {
  for (var c = d.length - 1; c > 0; c--) {
    var b = Math.floor(Math.random() * (c + 1));
    var a = d[c];
    d[c] = d[b];
    d[b] = a;
  }
  return d
};

答案 9 :(得分:19)

使用ES6语法可以缩短部分答案。

ES6 Pure,Iterative

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};

我个人使用这个功能,因为它纯粹,相对简单,并且根据我在Google Chrome上的测试效率最高(与其他纯版本相比)。

随机播放阵列

function getShuffledArr (array){
    for (let i = array.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [array[i], array[rand]] = [array[rand], array[i]]
    }
}

可靠性和性能

正如您在本页中所看到的,过去提供的解决方案不正确。因此,考虑到可靠性和性能,我编写了以下函数来测试任何纯(无副作用)数组随机化函数。我用它来测试这个答案中提出的所有选项。

function testShuffledArrayFun(getShuffledArrayFun){
    const arr = [0,1,2,3,4,5,6,7,8,9]

    let 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 = 1000000
    for (let i=0 ; i<n ; i++){
        //   We'll call getShuffledArrayFun n times. 
        //   And for each iteration, we'll increment the counter. 
        const 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}`)
}

Typescript - 纯数组随机化函数的类型

您可以使用以下任一方法。

type GetShuffledArr= <T>(arr:Array<T>) => Array<T> 
interface IGetShuffledArr{
    <T>(arr:Array<T>): Array<T>
}

其他选项

ES6 Pure,Recursive

const getShuffledArr = arr => {
    if (arr.length === 1) {return arr};
    const rand = Math.floor(Math.random() * arr.length);
    return [arr[rand], ...getShuffledArr(arr.filter((_, i) => i != rand))];
};

此版本的效率低于迭代纯版本。

ES6 Pure使用array.map

function getShuffledArr (arr){
    return [...arr].map( (_, i, arrCopy) => {
        var rand = i + ( Math.floor( Math.random() * (arrCopy.length - i) ) );
        [arrCopy[rand], arrCopy[i]] = [arrCopy[i], arrCopy[rand]]
        return arrCopy[i]
    })
}

此版本的效率略低于迭代纯版本。

ES6 Pure使用array.reduce

function getShuffledArr (arr){
    return arr.reduce( 
        (newArr, _, i) => {
            var rand = i + ( Math.floor( Math.random() * (newArr.length - i) ) );
            [newArr[rand], newArr[i]] = [newArr[i], newArr[rand]]
            return newArr
        }, [...arr]
    )
}

此版本的效率略低于迭代纯版本。

答案 10 :(得分:17)

这是最简单的一个,

function shuffle(array) {
  return array.sort(() => Math.random() - 0.5);
}

例如,您可以检查它here

答案 11 :(得分:14)

var shuffle = function(array) {
   temp = [];
   originalLength = array.length;
   for (var i = 0; i < originalLength; i++) {
     temp.push(array.splice(Math.floor(Math.random()*array.length),1));
   }
   return temp;
};

答案 12 :(得分:13)

我发现这个变种在&#34;被作者删除了#34;回答这个问题的重复。与已有许多赞成票的其他答案不同,这是:

  1. 实际上是随机的
  2. 非就地(因此shuffled名称而不是shuffle
  3. 此处尚未提供多种变体
  4. Here's a jsfiddle showing it in use

    Array.prototype.shuffled = function() {
      return this.map(function(n){ return [Math.random(), n] })
                 .sort().map(function(n){ return n[1] });
    }
    

答案 13 :(得分:9)

您可以轻松地做到:

// array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
// random
fruits.sort(function(a, b){return 0.5 - Math.random()});
// out
console.log(fruits);

请参考JavaScript Sorting Arrays

答案 14 :(得分:8)

递归解决方案:

function shuffle(a,b){
    return a.length==0?b:function(c){
        return shuffle(a,(b||[]).concat(c));
    }(a.splice(Math.floor(Math.random()*a.length),1));
};

答案 15 :(得分:7)

Fisher-Yates在javascript中随机播放。我在这里发布这个是因为使用两个实用函数(swap和randInt)来澄清算法与此处的其他答案相比。

function swap(arr, i, j) { 
  // swaps two elements of an array in place
  var 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);
  }
}

答案 16 :(得分:7)

首先,看看here,以便在javascript中对不同的排序方法进行精彩的视觉比较。

其次,如果您快速查看上面的链接,您会发现random order排序似乎与其他方法相比表现相对较好,同时实现起来非常简单快捷,如下所示:

function shuffle(array) {
  var random = array.map(Math.random);
  array.sort(function(a, b) {
    return random[array.indexOf(a)] - random[array.indexOf(b)];
  });
}

编辑:正如@gregers所指出的,比较函数是用值而不是索引来调用的,这就是你需要使用indexOf的原因。请注意,此更改使得代码不太适合较大的数组,因为indexOf在O(n)时间内运行。

答案 17 :(得分:7)

基准

让我们先看看结果,然后再看看下面 shuffle 的每个实现 -

  • splice

  • pop

  • inplace


拼接速度慢

任何在循环中使用 spliceshift 的解决方案都会非常缓慢。当我们增加数组的大小时,这一点尤其明显。在一个朴素的算法中,我们 -

  1. 在输入数组中获得一个 rand 位置 it
  2. t[i] 添加到输出
  3. splice 位置 i 来自数组 t

为了夸大缓慢的效果,我们将在包含一百万个元素的数组上演示这一点。下面的脚本将近30秒-

const shuffle = t =>
  Array.from(sample(t, t.length))

function* sample(t, n)
{ let r = Array.from(t)
  while (n > 0 && r.length)
  { const i = rand(r.length) // 1
    yield r[i]               // 2
    r.splice(i, 1)           // 3
    n = n - 1
  }
}

const rand = n =>
  Math.floor(Math.random() * n)

function swap (t, i, j)
{ let q = t[i]
  t[i] = t[j]
  t[j] = q
  return t
}

const size = 1e6
const bigarray = Array.from(Array(size), (_,i) => i)
console.time("shuffle via splice")
const result = shuffle(bigarray)
console.timeEnd("shuffle via splice")
document.body.textContent = JSON.stringify(result, null, 2)
body::before {
  content: "1 million elements via splice";
  font-weight: bold;
  display: block;
}


pop 很快

诀窍不是splice,而是使用超级高效的pop。为此,代替典型的 splice 调用,您 -

  1. 选择要拼接的位置,i
  2. t[i] 与最后一个元素 t[t.length - 1] 交换
  3. t.pop() 添加到结果中

现在我们可以在不到 100 毫秒的时间内shuffle处理一百万个元素 -

const shuffle = t =>
  Array.from(sample(t, t.length))

function* sample(t, n)
{ let r = Array.from(t)
  while (n > 0 && r.length)
  { const i = rand(r.length) // 1
    swap(r, i, r.length - 1) // 2
    yield r.pop()            // 3
    n = n - 1
  }
}

const rand = n =>
  Math.floor(Math.random() * n)

function swap (t, i, j)
{ let q = t[i]
  t[i] = t[j]
  t[j] = q
  return t
}

const size = 1e6
const bigarray = Array.from(Array(size), (_,i) => i)
console.time("shuffle via pop")
const result = shuffle(bigarray)
console.timeEnd("shuffle via pop")
document.body.textContent = JSON.stringify(result, null, 2)
body::before {
  content: "1 million elements via pop";
  font-weight: bold;
  display: block;
}


甚至更快

上面 shuffle 的两个实现产生了一个 new 输出数组。输入数组未修改。这是我更喜欢的工作方式,但是您可以通过原地洗牌来进一步提高速度。

不到 10 毫秒内低于 shuffle 一百万个元素 -

function shuffle (t)
{ let last = t.length
  let n
  while (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] = q
  return t
}

const size = 1e6
const 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;
}

答案 18 :(得分:6)

一个不改变源数组

的shuffle函数

更新:我建议使用相对简单(不是来自复杂性视角)和简短算法这对于小型数组来说会很好,但是当处理大型数组时,它肯定会比经典的 Durstenfeld 算法花费更多。你可以在对这个问题的一个热门回复中找到 Durstenfeld

原始答案:

如果不希望你的shuffle函数改变源数组,你可以将它复制到局部变量,然后用一个简单的改组逻辑

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;
}

答案 19 :(得分:5)

arr1.sort(() => Math.random() - 0.5);

答案 20 :(得分:5)

function shuffle(array) {
  array.sort(() => Math.random() - 0.5);
}

let arr = [1, 2, 3];
shuffle(arr);
alert(arr);

https://javascript.info/task/shuffle

答案 21 :(得分:5)

Fisher-Yates的另一个实现,使用严格模式:

function shuffleArray(a) {
    "use strict";
    var i, t, j;
    for (i = a.length - 1; i > 0; i -= 1) {
        t = a[i];
        j = Math.floor(Math.random() * (i + 1));
        a[i] = a[j];
        a[j] = t;
    }
    return a;
}

答案 22 :(得分:5)

所有其他答案都基于Math.random(),它很快但不适合加密级别的随机化。

以下代码使用众所周知的Fisher-Yates算法,同时将Web Cryptography API用于加密级别的随机化

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));

答案 23 :(得分:4)

虽然已经建议了许多实现,但我觉得我们可以使用forEach循环使它更短更容易,所以我们不需要担心计算数组长度而且我们可以安全地避免使用临时变量

ClientMessage[messageID=8, durable=false, address=q49589558,userID=null,properties=TypedProperties[id=13,phone=phone,name=name]]

答案 24 :(得分:4)

使用ES6功能的现代短内联解决方案:

['a','b','c','d'].map(x => [Math.random(), x]).sort(([a], [b]) => a - b).map(([_, x]) => x);

(用于教育目的)

答案 25 :(得分:4)

CoolAJ86 answer的一个简单修改,它不会修改原始数组:

 /**
 * 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;
};

答案 26 :(得分:4)

只是想要一个馅饼。在这里,我提出了Fisher Yates shuffle的递归实现(我认为)。它给出了均匀的随机性。

注意:对于正实数,~~(双波浪形运算符)实际上与Math.floor()的行为类似。只是捷径。

&#13;
&#13;
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])));
&#13;
&#13;
&#13;

答案 27 :(得分:3)

使用Fisher-Yates随机播放算法和ES6:

// Original array
let array = ['a', 'b', 'c', 'd'];

// Create a copy of the original array to be randomized
let shuffle = [...array];

// Defining function returning random value from i to N
const getRandomValue = (i, N) => Math.floor(Math.random() * (N - i) + i);

// Shuffle a pair of two elements at random position j
shuffle.forEach( (elem, i, arr, j = getRandomValue(i, arr.length)) => [arr[i], arr[j]] = [arr[j], arr[i]] );

console.log(shuffle);
// ['d', 'a', 'b', 'c']

答案 28 :(得分:3)

有趣的是没有非变异的递归回答:

&#13;
&#13;
var shuffle = arr => {
  const recur = (arr,currentIndex)=>{
    console.log("What?",JSON.stringify(arr))
    if(currentIndex===0){
      return arr;
    }
    const randomIndex = Math.floor(Math.random() * currentIndex);
    const swap = arr[currentIndex];
    arr[currentIndex] = arr[randomIndex];
    arr[randomIndex] = swap;
    return recur(
      arr,
      currentIndex - 1
    );
  }
  return recur(arr.map(x=>x),arr.length-1);
};

var arr = [1,2,3,4,5,[6]];
console.log(shuffle(arr));
console.log(arr);
&#13;
&#13;
&#13;

答案 29 :(得分:3)

从理论的角度来看,在我看来,最优雅的做法是在 0 之间获得随机数n!-1 并计算从void*{0, 1, …, n!-1}的所有排列的一对一映射。只要你可以使用足够可靠的(伪)随机发生器来获得这样的数字而没有任何明显的偏差,你就可以获得足够的信息来实现你想要的而不需要其他几个随机数。

使用IEEE754双精度浮点数进行计算时,您可以期望随机生成器提供大约15个小数。由于您有 15!= 1,307,674,368,000 (13位数),因此您可以对包含最多15个元素的数组使用以下函数,并假设对于包含最多14个元素的数组没有明显的偏差。如果你处理一个固定大小的问题,需要多次计算这个shuffle操作,你可能想尝试以下代码,可能比其他代码更快,因为它只使用(0, 1, 2, …, n-1)一次(但它涉及多个复制操作)。

以下功能将不会被使用,但无论如何我都会给它;它根据此消息中使用的一对一映射(枚举permeations时最自然的映射)返回Math.random的给定排列的索引;它最多可以使用16个元素:

(0, 1, 2, …, n-1)

上一个函数的倒数(您自己的问题所需)低于;它旨在与多达16个元素一起使用;它返回function permIndex(p) { var fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000]; var tail = []; var i; if (p.length == 0) return 0; for(i=1;i<(p.length);i++) { if (p[i] > p[0]) tail.push(p[i]-1); else tail.push(p[i]); } return p[0] * fact[p.length-1] + permIndex(tail); } n 的排列:

(0, 1, 2, …, s-1)

现在,你想要的只是:

function permNth(n, s) {
    var fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000];
    var i, j;
    var p = [];
    var q = [];
    for(i=0;i<s;i++) p.push(i);
    for(i=s-1; i>=0; i--) {
        j = Math.floor(n / fact[i]);
        n -= j*fact[i];
        q.push(p[j]);
        for(;j<i;j++) p[j]=p[j+1];
    }
    return q;
}

它应该适用于多达16个元素并且具有一点理论偏差(尽管从实际角度来看不明显);它可以被视为完全可用于15个元素;对于包含少于14个元素的数组,您可以放心地认为绝对没有偏见。

答案 30 :(得分:3)

最短的function arrayShuffle(o) { for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } 函数

if let imageData = partners[indexPath.row].userPhoto as? Data {
    partnerPhoto = UIImage(data: imageData)
} else {
    partnerPhoto = UIImage() //just to prevent the crash
    debugPrint("imageData is incorrect")
    //You can set here some kind of placeholder image instead of broken imageData here like UIImage(named: "placeholder.png")
}
cell.fillWithContent(partnerPhoto: partnerPhoto)
return cell

答案 31 :(得分:2)

罗纳德费舍尔和弗兰克耶茨洗牌

  

ES2015(ES6)发布

Array.prototype.shuffle2 = function () {
    this.forEach(
        function (v, i, a) {
            let j = Math.floor(Math.random() * (i + 1));
            [a[i], a[j]] = [a[j], a[i]];
        }
    );
    return this;
}
  

Jet优化的ES2015(ES6)版本

Array.prototype.shuffle3 = function () {
    var m = this.length;
    while (m) {
        let i = Math.floor(Math.random() * m--);
        [this[m], this[i]] = [this[i], this[m]];
    }
    return this;
}

答案 32 :(得分:2)

function shuffleArray(array) {
        // Create a new array with the length of the given array in the parameters
        const newArray = array.map(() => null);

        // Create a new array where each index contain the index value
        const arrayReference = array.map((item, index) => index);

        // Iterate on the array given in the parameters
        array.forEach(randomize);
        
        return newArray;

        function randomize(item) {
            const randomIndex = getRandomIndex();

            // Replace the value in the new array
            newArray[arrayReference[randomIndex]] = item;
            
            // Remove in the array reference the index used
            arrayReference.splice(randomIndex,1);
        }

        // Return a number between 0 and current array reference length
        function 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]));

答案 33 :(得分:2)

var shuffledArray = function(inpArr){
    //inpArr - is input array
    var arrRand = []; //this will give shuffled array
    var arrTempInd = []; // to store shuffled indexes
    var max = inpArr.length;
    var min = 0;
    var tempInd;
    var i = 0;

    do{
        //generate random index between range
        tempInd = Math.floor(Math.random() * (max - min));
        //check if index is already available in array to avoid repetition
        if(arrTempInd.indexOf(tempInd)<0){
            //push character at random index
            arrRand[i] = inpArr[tempInd];
            //push random indexes
            arrTempInd.push(tempInd);
            i++;
        }
    }
    // check if random array length is equal to input array length
    while(arrTempInd.length < max){
        return arrRand; // this will return shuffled Array
    }
};

只需将数组传递给函数,然后返回获取混洗数组

答案 34 :(得分:2)

随机化数组

 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 tempArr 
     tempArr.push(arr.splice(Math.floor(Math.random()*arr.length),1)[0]);
 }

 // Push the remaining item onto tempArr 
 tempArr.push(arr[0]); 
 arr=tempArr; 

答案 35 :(得分:2)

使用array.splice()

随机化数组
function shuffleArray(array) {
   var temp = [];
   var len=array.length;
   while(len){
      temp.push(array.splice(Math.floor(Math.random()*array.length),1)[0]);
      len--;
   }
   return temp;
}
//console.log("Here >>> "+shuffleArray([4,2,3,5,8,1,0]));

demo

答案 36 :(得分:2)

Array.prototype.shuffle=function(){
   var len = this.length,temp,i
   while(len){
    i=Math.random()*len-- |0;
    temp=this[len],this[len]=this[i],this[i]=temp;
   }
   return this;
}

答案 37 :(得分:2)

考虑将其应用于 in loco 或新的不可变数组,遵循其他解决方案,这是一个建议的实现:

using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{

    public Button button1;
    public Button button2;
    public Button button3;

    void OnEnable()
    {
        //Register Button Events
        button1.onClick.AddListener(() => buttonCallBack(button1));
        button2.onClick.AddListener(() => buttonCallBack(button2));
        button3.onClick.AddListener(() => buttonCallBack(button3));

    }

    private void buttonCallBack(Button buttonPressed)
    {
        if (buttonPressed == button1)
        {
            //Your code for button 1
            //Call your SetBuilding(GameObject building) function for any button
            SetBuilding(someGameOBject);
        }

        if (buttonPressed == button2)
        {
            //Your code for button 2
        }

        if (buttonPressed == button3)
        {
            //Your code for button 3
        }
    }

    void OnDisable()
    {
        //Un-Register Button Events
        button1.onClick.RemoveAllListeners();
        button2.onClick.RemoveAllListeners();
        button3.onClick.RemoveAllListeners();
    }
}

答案 38 :(得分:2)

通过使用 shuffle-array 模块,您可以随机播放阵列。这是一个简单的代码。

var shuffle = require('shuffle-array'),
 //collection = [1,2,3,4,5];
collection = ["a","b","c","d","e"];
shuffle(collection);

console.log(collection);

希望这有帮助。

答案 39 :(得分:2)

// 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];
    })
}

答案 40 :(得分:2)

我使用这两种方法:

此方法不修改原数组

shuffle(array);

function shuffle(arr) {
    var len = arr.length;
    var d = len;
    var array = [];
    var k, i;
    for (i = 0; i < d; i++) {
        k = Math.floor(Math.random() * len);
        array.push(arr[k]);
        arr.splice(k, 1);
        len = arr.length;
    }
    for (i = 0; i < d; i++) {
        arr[i] = array[i];
    }
    return arr;
}

var arr = ["a", "b", "c", "d"];
arr = shuffle(arr);
console.log(arr);

此方法修改原数组

array.shuffle();

Array.prototype.shuffle = function() {
    var len = this.length;
    var d = len;
    var array = [];
    var k, i;
    for (i = 0; i < d; i++) {
        k = Math.floor(Math.random() * len);
        array.push(this[k]);
        this.splice(k, 1);
        len = arr.length;
    }
    for (i = 0; i < d; i++) {
        this[i] = array[i];
    }
}

var arr = ["a", "b", "c", "d"];
arr.shuffle();
console.log(arr);

答案 41 :(得分:2)

我看到没有人提供可以连接的解决方案,而不是扩展Array原型(a bad practice)。使用稍微鲜为人知的reduce(),我们可以轻松地以允许连接的方式进行混洗:

var randomsquares = [1, 2, 3, 4, 5, 6, 7].reduce(shuffle).map(n => n*n);

您可能希望传递第二个参数[],否则如果您尝试在空数组上执行此操作,则会失败:

// Both work. The second one wouldn't have worked as the one above
var 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 wanted
  for (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;
}

您可以在 in JSFiddle 或此处看到它:

&#13;
&#13;
var shuffle = (all, one, i, orig) => {
    if (i !== 1) return all;

    // You could use here other random algorithm here
    for (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));
}
&#13;
&#13;
&#13;

答案 42 :(得分:2)

我正在考虑将oneliner粘贴到控制台中。 .sort的所有技巧都给出了错误的结果,这是我的实现:

 ['Bob', 'Amy', 'Joy'].map((person) => `${Math.random().toFixed(10)}${person}`).sort().map((person) => person.substr(12));

但是不要在生产代码中使用它,它不是最佳的,只适用于字符串。

答案 43 :(得分:1)

重建整个数组,一个接一个地将每个元素放置在随机位置。

[1,2,3].reduce((a,x,i)=>{a.splice(Math.floor(Math.random()*(i+1)),0,x);return a},[])

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);

答案 44 :(得分:1)

Fisher-Yates的这种变化稍微有点效率,因为它避免了自己交换元素:

function shuffle(array) {
  var elementsRemaining = array.length, temp, randomIndex;
  while (elementsRemaining > 1) {
    randomIndex = Math.floor(Math.random() * elementsRemaining--);
    if (randomIndex != elementsRemaining) {
      temp = array[elementsRemaining];
      array[elementsRemaining] = array[randomIndex];
      array[randomIndex] = temp;
    }
  }
  return array;
}

答案 45 :(得分:1)

我们仍将在2019年对数组进行改组,所以我的方法来了,这对我来说似乎很整洁,fast

const src = [...'abcdefg'];

const shuffle = arr => arr.reduceRight((res,_,__,arr) => [...res,arr.splice(~~(Math.random()*arr.length),1)[0]],[]);

console.log(shuffle(src));
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

答案 46 :(得分:1)

随机推动或取消移动(在开头添加)。

['a', 'b', 'c', 'd'].reduce((acc, el) => {
  Math.random() > 0.5 ? acc.push(el) : acc.unshift(el);
  return acc;
}, []);

答案 47 :(得分:1)

对于我们中那些不那么有天赋但可以接触到洛达奇奇迹的人来说,lodash.shuffle这样的东西。

答案 48 :(得分:1)

我自己编写了一个随机播放功能。这里的区别是它永远不会重复一个值(检查代码): -

function shuffleArray(array) {
 var newArray = [];
 for (var i = 0; i < array.length; i++) {
     newArray.push(-1);
 }

 for (var j = 0; j < array.length; j++) {
    var id = Math.floor((Math.random() * array.length));
    while (newArray[id] !== -1) {
        id = Math.floor((Math.random() * array.length));
    }

    newArray.splice(id, 1, array[j]);
 }
 return newArray; }

答案 49 :(得分:1)

d3.js提供了built-inFisher–Yates shuffle版本:

console.log(d3.shuffle(["a", "b", "c", "d"]));
<script src="http://d3js.org/d3.v5.min.js"></script>

  

d3.shuffle(array [,lo [,hi]])<>

     

使用Fisher–Yates shuffle随机化指定数组的顺序。

答案 50 :(得分:0)

我发现这很有用:

const shuffle = (array: any[]) => {
    return array.slice().sort(() => Math.random() - 0.5);
  }
        
console.log(shuffle([1,2,3,4,5,6,7,8,9,10]));
// Output: [4, 3, 8, 10, 1, 7, 9, 2, 6, 5]

答案 51 :(得分:0)

  

随机播放字符串数组:

shuffle = (array) => {
  let counter = array.length, temp, index;
  while ( counter > 0 ) {
    index = Math.floor( Math.random() * counter );
    counter--;
    temp = array[ counter ];
    array[ counter ] = array[ index ];
    array[ index ] = temp;
  }
  return array;
 }

答案 52 :(得分:0)

这里有简单的while循环

 function ShuffleColor(originalArray) {
        let shuffeledNumbers = [];
        while (shuffeledNumbers.length <= originalArray.length) {
            for (let _ of originalArray) {
                const randomNumb = Math.floor(Math.random() * originalArray.length);
                if (!shuffeledNumbers.includes(originalArray[randomNumb])) {
                    shuffeledNumbers.push(originalArray[randomNumb]);
                }
            }
            if (shuffeledNumbers.length === originalArray.length)
                break;
        }
        return shuffeledNumbers;
    }
const colors = [
    '#000000',
    '#2B8EAD',
    '#333333',
    '#6F98A8',
    '#BFBFBF',
    '#2F454E'
]
ShuffleColor(colors)

答案 53 :(得分:0)

 const arr = [
  { index: 0, value: "0" },
  { index: 1, value: "1" },
  { index: 2, value: "2" },
  { index: 3, value: "3" },
];
let shuffle = (arr) => {
  let set = new Set();
  while (set.size != arr.length) {
    let rand = Math.floor(Math.random() * arr.length);
    set.add(arr[rand]);
  }
  console.log(set);
};
shuffle(arr);

答案 54 :(得分:0)

&#13;
&#13;
$=(m)=>console.log(m);

//----add this method to Array class 
Array.prototype.shuffle=function(){
  return this.sort(()=>.5 - Math.random());
};

$([1,65,87,45,101,33,9].shuffle());
$([1,65,87,45,101,33,9].shuffle());
$([1,65,87,45,101,33,9].shuffle());
$([1,65,87,45,101,33,9].shuffle());
$([1,65,87,45,101,33,9].shuffle());
&#13;
&#13;
&#13;

答案 55 :(得分:0)

我想分享一百万种解决这个问题的方法=)

function shuffleArray(array = ["banana", "ovo", "salsicha", "goiaba", "chocolate"]) {
const newArray = [];
let number = Math.floor(Math.random() * array.length);
let count = 1;
newArray.push(array[number]);

while (count < array.length) {
    const newNumber = Math.floor(Math.random() * array.length);
    if (!newArray.includes(array[newNumber])) {
        count++;
        number = newNumber;
        newArray.push(array[number]);
    }
}

return newArray;

}

答案 56 :(得分:0)

使用Ramda的功能解决方案。

const {map, compose, sortBy, prop} = require('ramda')

const shuffle = compose(
  map(prop('v')),
  sortBy(prop('i')),
  map(v => ({v, i: Math.random()}))
)

shuffle([1,2,3,4,5,6,7])

答案 57 :(得分:0)

使用递归JS改组数组。

这不是最佳的实现,但是它是递归的并且尊重不变性。

const randomizer = (array, output = []) => {
    const arrayCopy = [...array];
    if (arrayCopy.length > 0) {    
        const idx = Math.floor(Math.random() * arrayCopy.length);
        const select = arrayCopy.splice(idx, 1);
        output.push(select[0]);
        randomizer(arrayCopy, output);
    }
    return output;
};

答案 58 :(得分:0)

社区说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 

在100个不同的随机数组中。 (我的分析结果)

{ player> 1   2   3  4   5   6
   '1': [ 36, 12, 17, 16, 9, 10 ],
   '2': [ 15, 36, 12, 18, 7, 12 ],
   '3': [ 11, 8, 22, 19, 17, 23 ],
   '4': [ 9, 14, 19, 18, 22, 18 ],
   '5': [ 12, 19, 15, 18, 23, 13 ],
   '6': [ 17, 11, 15, 11, 22, 24 ]
}  
// player 1 got > 1(36 times),2(15 times),...,6(17 times)
// ... 
// ...
// player 6 got > 1(10 times),2(12 times),...,6(24 times)

如您所见,它不是那么随机! ...... 请勿使用此方法!


如果您多次测试,您会发现玩家1多次获得(数字1)!
而玩家6多数时候获得了(数字6)!

答案 59 :(得分:0)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
    ren = Math.random();
    if (ren == 0.5) return 0;
    return ren > 0.5 ? 1 : -1
})

答案 60 :(得分:-1)

使用排序方法和数学方法:

var arr =  ["HORSE", "TIGER", "DOG", "CAT"];
function shuffleArray(arr){
  return arr.sort( () => Math.floor(Math.random() * Math.floor(3)) - 1)  
}

// every time it gives random sequence
shuffleArr(arr);
// ["DOG", "CAT", "TIGER", "HORSE"]
// ["HORSE", "TIGER", "CAT", "DOG"]
// ["TIGER", "HORSE", "CAT", "DOG"]

答案 61 :(得分:-1)

//doesn change array
Array.prototype.shuffle = function () {
    let res = [];
    let copy = [...this];

    while (copy.length > 0) {
        let index = Math.floor(Math.random() * copy.length);
        res.push(copy[index]);
        copy.splice(index, 1);
    }

    return res;
};

let a=[1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(a.shuffle());

答案 62 :(得分:-1)

一种快速,美观的解决方案(可能不是最有效的方法)

const data = [1, 2, 3, 4, 5, 6];
const randomizedData = data
  .map(d => ({r: Math.random(), d}))
  .sort((a, b) => a.r - b.r)
  .map(d => d.d);

console.log(randomizedData);