C++ No-repeat random number generator

前端 未结 3 1739
慢半拍i
慢半拍i 2020-12-12 05:38

I need to create algorithm implementation in C++ to generate random numbers to f.e table without repeat and list.

I created something code like that but it\'s stop w

3条回答
  •  既然无缘
    2020-12-12 06:39

    I just want to state some other solutions to the following problems, which may work faster (or with some shorter code) (in some cases).

    Imagine the case where you need all the elements of the set {0, 1, .., n - 1}, probability of choosing the last non-chosen element(in last iteration) is equal to 1/n, expected value is then n iterations for picking only one element.

    1. vector p;
      for(int i = 0; i < n; i++) p.push_back(i);
      random_shuffle(p.begin(), p.end();
      

    and then you can take first K elements of vector p (or whole vector, if you need the whole permutation).

    1. In every iteration, you can pick a random number i between 1 and numbers_left (N - numbers_already_chosen), and then take i-th number that hasn't been already picked. It may also be inefficient, but using some binary search + binary indexed tree, you could get to O(Nlog^2N), maybe even better.

提交回复
热议问题