C++ function for picking from a list where each element has a distinct probability

前端 未结 2 528
庸人自扰
庸人自扰 2020-12-03 09:04

I have an array of structs and one of the fields in the struct is a float. I want to pick one of the structs where the probability of picking it is relative to the value of

相关标签:
2条回答
  • 2020-12-03 09:17
    float p = (rand() / static_cast<float>(RAND_MAX)) * total_probability;
    s* current = &sArray[0];
    while ( (p -= current->probability) > 0)
        ++current;
    // `current` now points to your chosen target
    
    0 讨论(0)
  • 2020-12-03 09:23

    Find out RAND_MAX as you say. Generate a random number up to RAND_MAX. Iterate through the array counting up the probabilities until you equal or exceed your generated random number. (With only 50 element performance shouldn't be an issue, otherwise store the sums of the probabilities once in another array and then do a bisection search into that for the random value.)

    0 讨论(0)
提交回复
热议问题