Pick a unique random subset from a set of unique values

前端 未结 3 649
慢半拍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:35

    Most of the time, the method provided by Kerrek is sufficient. But if N is very large, and M is orders of magnitude smaller, the following method may be preferred.

    Create a set of unsigned integers, and add random numbers to it in the range [0,N-1] until the size of the set is M. Then use the elements at those indexes.

    std::set indices;
    while (indices.size() < M)
        indices.insert(RandInt(0,N-1));
    

提交回复
热议问题