2018年9月18日 星期二

Algorithm :: Fisher–Yates shuffle

給定一個數列,要輸出隨機排列的序列:
方法1. c++提供 next_permutation()
http://www.cplusplus.com/reference/algorithm/next_permutation/



















結果:











方法2. 逐一從input array中隨機挑一個複製到output array並且刪掉原本的element
缺點:如果input array是vector,erase會很花時間,而且每次隨機挑選都要重新跑rand(),很耗

方法3. Fisher Yate's Algorithm
https://gaohaoyang.github.io/2016/10/16/shuffle-algorithm/
https://www.cnblogs.com/zichi/p/Fisher-Yates-shuffle.html

假設input array的size = n,index = 0:n1
for( i = n-1: 1){
    隨機產生[0:i]的數字j,把input[i]和input[j] 交換
}

有點像蓄水池理論,要證明就一個一個證,index = 0 的這個element直到最後都沒有被換到的機率是1/n




沒有留言:

張貼留言