Problem:
To write a random elements generator which can randomly pick elements from given array following the weights given by the user.
Input:
1. Array of items
2. Array of integers indicating weight for each item
Output:
Samples following given weight distribution
Example:
Say
Items = ["Apple", "Banana", "Chikoo"]
Weights = [3, 1, 2]
Then approximately 3/6 of the output samples should be "Apple", 1/6 should be "Banana", 2/6 should be "Chikoo".
Solution:
1. Construct cummulutive weights array.
2. Generate random number sample between 1 and sum(weights)
3. Find index at which cummulative weight is less than or equal to sample.
4. Output item at this index.
Code:
Java source code is available at https://gist.github.com/yogidevendra/f66f64a26ac37f8c2077
To write a random elements generator which can randomly pick elements from given array following the weights given by the user.
Input:
1. Array of items
2. Array of integers indicating weight for each item
Output:
Samples following given weight distribution
Example:
Say
Items = ["Apple", "Banana", "Chikoo"]
Weights = [3, 1, 2]
Then approximately 3/6 of the output samples should be "Apple", 1/6 should be "Banana", 2/6 should be "Chikoo".
Solution:
1. Construct cummulutive weights array.
2. Generate random number sample between 1 and sum(weights)
3. Find index at which cummulative weight is less than or equal to sample.
4. Output item at this index.
Code:
Java source code is available at https://gist.github.com/yogidevendra/f66f64a26ac37f8c2077
No comments:
Post a Comment