简体   繁体   English

费舍尔·耶茨的Java随机播放

[英]Fisher–Yates Shuffle in Javascript

New to JS and currently learning in college. JS的新手,目前正在大学学习。 For my current JS project, I am building a memory card game. 对于当前的JS项目,我正在构建一个存储卡游戏。 I started to think on how to randomly shuffle the cards, and I got close to what Fisher–Yates Shuffle algorithm does - the second program on this page . 我开始考虑如何随机洗牌,并且我接近Fisher-Yates洗牌算法的作用- 此页上的第二个程序。 However, I don't understand what the [0] does after the splice method exactly. 但是,我不完全理解拼接方法后[0]的作用。 Is it what shifts/compacts the array? 是移动/压缩数组的原因吗? If yes, I can't find other examples/documentations about that. 如果是,我找不到其他有关此的示例/文档。

function shuffle(array) {
  var copy = [], n = array.length, i;

  // While there remain elements to shuffle…
  while (n) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * n--);

    // And move it to the new array.
    copy.push(array.splice(i, 1)[0]);
  }

  return copy;
}

array.splice(i, 1) cuts out the i -th element of array and returns it as a single-value array (just like array.splice(i, 2) would cut out i -th and i+1 -th element and return them as a two-element array). array.splice(i, 1)切出arrayi个元素并将其作为单值数组返回(就像array.splice(i, 2)一样,切出第i个和第i+1个元素)并将它们作为两个元素的数组返回)。 Then [0] , the simple indexing operation, picks that single element from that array (as we don't need an array); 然后,简单的索引操作[0]从该数组中选择单个元素(因为我们不需要数组); this single element is then added to copy using copy.push . 然后使用copy.push copy单个元素添加到copy中。

More familiar uses of the indexing operation: 索引操作的更常见用法:

array = [4, 7, 2, 10];
array[0]
// => 4
array[1]
// => 7

array = [18];
array[0]
// => 18

array.splice() returns an array, but while shuffling you want to take a random card from an unknown position and put it inside the new array(shuffled one). array.splice()返回一个数组,但是在改组时,您想从一个未知的位置拿一张随机的卡,并将其放入新的数组中(改组一个)。 Now the catch is you don't want to add the similar array again by doing copy.push(array.splice(i, 1) as this will add the entire returned array to copy array and the randomness of your shuffle will get reduced which in turn will cause dependent result in your game because the array will be similar(~) to last one with just few bits flipped. Adding [0] to array.splice(i, 1) ensures that you are only copying one element from the entire result array returned at time, which results in greater randomness. 现在的问题是,您不想通过执行copy.push(array.splice(i, 1)来再次添加类似的数组copy.push(array.splice(i, 1)因为这会将整个返回的数组添加到copy数组中,并且随机播放的随机性会降低反过来会在您的游戏中导致从属结果,因为数组将与最后一个数组相似(〜),但只翻转了几位。在array.splice(i, 1)添加[0]可确保您仅从数组中复制一个元素。整个结果数组会及时返回,从而导致更大的随机性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM