The conceptually simplest solution would be to create a list where each element occurs as many times as its weight, so
fruits = [apple, apple, apple, apple, orange, orange, lemon]
Then use whatever functions you have at your disposal to pick a random element from that list (e.g. generate a random index within the proper range). This is of course not very memory efficient and requires integer weights.
Another, slightly more complicated approach would look like this:
Calculate the cumulative sums of weights:
intervals = [4, 6, 7]
Where an index of below 44 represents an apple, 44 to below 66 an orange and 66 to below 77 a lemon.
- Generate a random number
nin the range of0tosum(weights). - Go through the list of cumulative sums from start to finish to find the first item whose cumulative sum is above
n. The corresponding fruit is your result.
This approach requires more complicated code than the first, but less memory and computation and supports floating-point weights.
For either algorithm, the setup-step can be done once for an arbitrary number of random selections.