Algorithm to select a single, random combination of values?

后端 未结 7 1019
傲寒
傲寒 2020-11-22 14:04

Say I have y distinct values and I want to select x of them at random. What\'s an efficient algorithm for doing this? I could just call rand(

7条回答
  •  攒了一身酷
    2020-11-22 14:50

    Here is a simple way to do it which is only inefficient if Y is much larger than X.

    void randomly_select_subset(
        int X, int Y,
        const int * inputs, int X, int * outputs
    ) {
        int i, r;
        for( i = 0; i < X; ++i ) outputs[i] = inputs[i];
        for( i = X; i < Y; ++i ) {
            r = rand_inclusive( 0, i+1 );
            if( r < i ) outputs[r] = inputs[i];
        }
    }
    

    Basically, copy the first X of your distinct values to your output array, and then for each remaining value, randomly decide whether or not to include that value.

    The random number is further used to choose an element of our (mutable) output array to replace.

提交回复
热议问题