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

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

Join Date
Oct 2012
Posts
19
Rep Power
0

#### (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:
Code:
```(pseudocode)
i = rand(1,100)
if( i <= 20)
choose item1
else if(i >20 and i <=50)
choose item2
else
choose item3```
but the list of items is dynamic and there could potentially be a lot of items.

2. 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.
Code:
```   [CDF =: +/\2r10 3r10 5r10  NB. form a cumulative sum of the probabilities
1r5 1r2 1

[R =: ?0  NB. get a random number
0.199335

CDF I. R  NB. index of R in CDF
0

[INDEX =: CDF I. R  NB. index of R in CDF
0

INDEX { ;:'item1 item2 item3'  NB. use index for selection
┌─────┐
│item1│
└─────┘```