在 javascript 中使用混洗算法跟踪索引

tracking indexes with a shuffle algorithm in javascript

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

Fiddle: 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 洗牌算法:

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

您可以打乱一个索引数组,然后将其用作您关心的两个数组的索引:

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

只需打乱一个索引数组 indices = [0, 1, 2, ...],然后使用它通过 array[indices[i]].

访问您要按相同排列打乱的数组