I have a bag that has the following:
- 6 red marbles
- 5 green marbles
- 2 blue marbles
I want to remove a random marble from the bag, record it color, and repeat until no more marbles are left in the bag:
- sort the counts
- bag = {2:blue, 5:green, 6:red}
- compute the cumulative counts
- cumulative = {2:blue, 7:green, 13:red}
- pick a random number in [0, max cumulative count]
- rand(0, 13) = 3
- find insertion point index of this integer using binary search
- i = 1
- record the color corresponding to this index
- green
- reduce that count by 1
- bag = {2:blue, 4:green, 6:red}
- repeat until no more marbles in bag
Is this a good way to do this or are there more efficient ways in terms of time complexity?
Aucun commentaire:
Enregistrer un commentaire