在javascript

时间:2016-06-23 02:19:18

标签: javascript arrays algorithm shuffle

我有一个简单的字符串数组,看起来像下面那个和相应的新数组。我需要完成的是使用简单的shuffle算法(如下所示)来对简单数组进行洗牌,但是我需要使用相同的shuffle来重新排列相应的新数组,这是每个索引的结果会是相同的。这可能会令人困惑,所以请看下面的示例输出,它应该变得清晰。这种算法甚至可以用Fisher-Yates洗牌吗?

小提琴:here

在:

var simple_arr = ["701", "702", "703", "704", "705", "706", "707", "708"];
var new_arr = ["A1","A2","A3","A4","A5","A6","A7","A8"];

之后:

var after_simple_arr = ["701", "708", "702", "705", "703", "706", "704", "707"];
var after_new_arr = ["A1","A8","A2","A5","A3","A6","A4","A7"];

Fisher-Yates shuffle算法:

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

2 个答案:

答案 0 :(得分:1)

您可以随机播放索引数组,然后将其用作您关注的两个数组的索引:

var ids = [];
for (var i = 0; i < simple_arr.length; i++) {
    ids.push(i);
}
ids = shuffle(ids);
var dat1 = [];
var dat2 = [];
for (var i = 0; i < ids.length; i++) {
    dat1.push(simple_arr[ids[i]]);
  dat2.push(new_arr[ids[i]]);
}
console.log("shuffled simple_arr: ", dat1);
console.log("shuffled new_arr: ", dat2);

答案 1 :(得分:0)

只需对索引数组indices = [0, 1, 2, ...]进行随机播放,然后通过array[indices[i]]使用它来访问由同一置换数组进行调整。