Write a function which has:
input: array of pairs (unique id and weight) length of N, K =< N
output: K random unique ids (from input array)
Note: being called many times frequency of appearing of some Id in the output should be greater the more weight it has.
Example: id with weight of 5 should appear in the output 5 times more often than id with weight of 1. Also, the amount of memory allocated should be known at compile time, i.e. no additional memory should be allocated.
My question is: how to solve this task?
EDIT
thanks for responses everybody!
currently I can’t understand how weight of pair affects frequency of appearance of pair in the output, can you give me more clear, “for dummy” explanation of how it works?
My short answer: in no way.
Just because the problem definition is incorrect. As Axn brilliantly noticed:
Anyway, when K is pretty small relative to N, calculated frequencies will be pretty close to theoretical values.
The task may be splitted on two subtasks:
Generate random numbers with a given distribution
sumOfWeights)[1; sumOfWeights]Code
Generate unique random numbers
Well known Durstenfeld-Fisher-Yates algorithm may be used for generation unique random numbers. See this great explanation.
It requires N bytes of space, so if N value is defined at compiled time, we are able to allocate necessary space at compile time.
Now, we have to combine these two algorithms. We just need to use our own
Random()function instead of standardrand()in unique numbers generation algorithm.Code
Usage
Output
Corner case when weights are actually ignored