# [C#] Get a item from a list probability-wise

• Say I have this class:

``````public class SomeRandomClass
{
public string test = "Test";
public int probability;
}
``````

And I have this list:

``````List<SomeRandomClass> list = new List<SomeRandomClass>()
{
new SomeRandomClass() { probability = 90 },
new SomeRandomClass() { probability = 60 }
};
``````

Now, how would I randomly (but weighing in the probabilities) select a item from the list? I have this code but it requires all the probabilities to add up to a 100:

``````int randomNumber = random.Next(0, 100);

int cumulative = 0;
for (int i = 0; i < list.Count; i++)
{
cumulative += list[i].probability;
if(randomNumber < cumulative)
{
// this is the one we want to choose.
break;
}
}
``````

I'm thinking changing the range for the random function from 0, 100 to 0, and the addition of all the probabilities. Would it work though?

• This post is deleted!

• If I understand the problem correctly, one way to do this is to loop through the list before generating the random number to calculate the total sum (just like you've done with cumulative, but leave any other logic out of the loop). Once that loop completes, use the resulting total as the upper bound for random.Next().

The link below may also provide useful information.
http://www.vcskicks.com/random-element.php

• @AHK1221
Try something like this:

``````// int totalProbability = myList.Sum(x => x.probability);
public static SomeRandomClass GetItem(List<SomeRandomClass> items, int totalProbability)
{
// totalProbability is the sum of all items' probability
int randomNumber = _rnd.Next(0, totalProbability);

SomeRandomClass selectedItem = null;

foreach (SomeRandomClass item in items)
{
if (randomNumber < item.Weight)
{
selectedItem = item;
break;
}

randomNumber = randomNumber - item.Weight;
}

return selectedItem;
}
``````

Looks like your connection to GTA5-Mods.com Forums was lost, please wait while we try to reconnect.