給定一個數列,要輸出隨機排列的序列:
方法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
訂閱:
張貼留言 (Atom)
-
(1) Vector Common method: vector<int> v; vector v(10, 0); // {0,0,0,0,0,0,0,0,0,0} v[i] // acc...
-
Inspire by Leetcode #239 https://leetcode.com/problems/sliding-window-maximum/description/ The purpose is the maintain a queue (FIFO) an...
-
Q: For a given size = n array, how to choose k element fairly? A: This is a rather easy question if n is small. What if the size is unkn...
沒有留言:
張貼留言