1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Rep Power

    (C#) More chance of picking certain items from randomized list

    Hey all,
    I'm working on a project in C# and I want to have an item be chosen from a list randomly, but with some items having more chance of being chosen than others - I've got some ideas of how to go about this but what would be the most efficient way? (The list could potentially be very long)

    So eg:
    Array: { "item1", "item2", "item3" }

    item1 has 20% chance of being chosen, item2 has 30% chance and item3 has 50% chance.

    I'm sure I could just go:
    i = rand(1,100)
    if( i <= 20)
        choose item1
    else if(i >20 and i <=50)
       choose item2
       choose item3
    but the list of items is dynamic and there could potentially be a lot of items.

    Thanks in advance!
  2. #2
  3. Contributing User

    Join Date
    Aug 2011
    Rep Power
    make an array with the sum of the prefixes of the probabilities, get a random number, use binary search to find the interval index into which it fits.
    In your example,
       [CDF =: +/\2r10 3r10 5r10  NB. form a cumulative sum of the probabilities
    1r5 1r2 1
       [R =: ?0  NB. get a random number
       CDF I. R  NB. index of R in CDF
       [INDEX =: CDF I. R  NB. index of R in CDF
       INDEX { ;:'item1 item2 item3'  NB. use index for selection
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo