我有一個簡單的字符串數組,它看起來像下面的一個和相應的新數組。我需要完成的是用簡單的隨機算法(如下面的算法)對簡單數組進行洗牌,但是我需要將相應的新數組與相同的隨機洗牌進行混洗,即每個索引的結果將是相同的。這可能會令人困惑,請看下面的示例輸出,它應該變得清晰。這種類型的算法甚至可以通過Fisher-Yates shuffle實現嗎?在javascript中使用shuffle算法跟蹤索引
小提琴: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"];
費雪耶茨洗牌算法:
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;
}
這是一個很好的解決方案,謝謝! @ZiyaoWei – NodeDeveloper102