2016-06-23 55 views
0

我有一個簡單的字符串數組,它看起來像下面的一個和相應的新數組。我需要完成的是用簡單的隨機算法(如下面的算法)對簡單數組進行洗牌,但是我需要將相應的新數組與相同的隨機洗牌進行混洗,即每個索引的結果將是相同的。這可能會令人困惑,請看下面的示例輸出,它應該變得清晰。這種類型的算法甚至可以通過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; 
} 

回答

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

這是一個很好的解決方案,謝謝! @ZiyaoWei – NodeDeveloper102

0

只是洗牌索引陣列indices = [0, 1, 2, ...],然後用它通過array[indices[i]]訪問您將要洗牌,由這同樣的置換陣列。