Answers for "randomly choosing numbers based on their weight"

C
0

choose random number with weight

int sum_of_weight = 0;
for(int i=0; i<num_choices; i++) {
   sum_of_weight += choice_weight[i];
}
int rnd = random(sum_of_weight);
for(int i=0; i<num_choices; i++) {
  if(rnd < choice_weight[i])
    return i;
  rnd -= choice_weight[i];
}
assert(!"should never get here");
Posted by: Guest on September-22-2021

Code answers related to "randomly choosing numbers based on their weight"

Code answers related to "C"

Browse Popular Code Answers by Language