2015-12-09 36 views
0

我已經看到了基於std::random_shuffle創建一個不重複的隨機數向量的方法,但是我需要實現一種替代方法。這是我的代碼:用不重複的隨機數填充矢量。爲什麼不工作?

std::vector<int> create_unrepeated_random(int v_size, int v_max) { 

    // Max index value must be grater than the number of vector size 
    assert(v_max > v_size); 

    std::vector<int> ret; 

    int val = 0; 

    for (int i = 0; i < v_size; i++) { 

    val = std::rand() % v_max; 

    // Keep generating new values until we generate one that is not already in 
    // output vector 
    if (ret.size() > 0) { 
     while (!std::binary_search(ret.begin(), ret.end(), val)) { 
     val = std::rand() % v_max; 
     } 
    } 

    ret.push_back(val); 

    } 


    assert ((int)ret.size() == v_size); 
    for (auto &v: ret) printf("%d ", v);printf("\n"); 

    return ret; 

} 

但是,這是行不通的,不知道爲什麼。有些數字有時候會重新顯示。

,但如果我改變while環路

while (std::binary_search(ret.begin(), ret.end(), val)) 

這造成重複隨機數的載體。這裏有什麼問題?

+1

對我來說,就像您在未排序的列表上使用二進制搜索一樣,這需要排序列表。當您生成不在列表中的新號碼時,您應該進行插入排序,以便列表中的號碼保持排序狀態。 –

+0

請參閱[如何在已排序的向量中插入值](http://stackoverflow.com/questions/15843525/how-do-you-insert-the-value-in-a-sorted-vector)進行討論以及[C++向量插入排序算法方法 - 將向量傳入方法](http://stackoverflow.com/questions/5709637/c-vector-insertion-sort-algorithm-method-pass-vector-into-method)。 –

+0

作爲一種改進,您可以將'vector'聲明更改爲'std :: vector ret(v_size);' – CinCout

回答

4
std::binary_search 

只適用於排序的範圍。使用std::find代替:

while (std::find(ret.begin(), ret.end(), val) != ret.end()) 

或者,您也可以使用std::unordered_set

std::unordered_set<int> ret; 
while (ret.size() < v_size) { 
    ret.insert(rand() % v_max); 
} 

請記住,這種方法生成的數字的順序將是不確定的,即可能小於向量方法隨機。如果你想要一個隨機數字的排序序列,請考慮std::set


備註:使用rand()不鼓勵在現代C++,雖然它可能會做玩具節目的伎倆。另請參見https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful