mardi 13 décembre 2016

Algorithm for iterating over random permutation

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:

  1. sort the counts
    • bag = {2:blue, 5:green, 6:red}
  2. compute the cumulative counts
    • cumulative = {2:blue, 7:green, 13:red}
  3. pick a random number in [0, max cumulative count]
    • rand(0, 13) = 3
  4. find insertion point index of this integer using binary search
    • i = 1
  5. record the color corresponding to this index
    • green
  6. reduce that count by 1
    • bag = {2:blue, 4:green, 6:red}
  7. 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