Pick a unique random subset from a set of unique values

前端 未结 3 639
慢半拍i
慢半拍i 2020-12-10 03:42

C++. Visual Studio 2010.

I have a std::vector V of N unique elements (heavy structs). How can efficiently pick M random, unique, elemen

3条回答
  •  攒了一身酷
    2020-12-10 04:32

    Create a random permutation of the range 0, 1, ..., N - 1 and pick the first M of them; use those as indices into your original vector.

    A random permutation is easily made with the standard library by using std::iota together with std::random_shuffle:

    std::vector v; // given
    
    std::vector indices(V.size());
    std::iota(indices.begin(), indices.end(), 0);
    std::random_shuffle(indices.begin(), indices.end());
    
    // use V[indices[0]], V[indices[1]], ..., V[indices[M-1]]
    

    You can supply random_shuffle with a random number generator of your choice; check the docu­men­tation for details.

提交回复
热议问题