Skip to content

Instantly share code, notes, and snippets.

@snlehton
Last active June 10, 2017 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snlehton/0fd9b2138f0f513b36119926f9ed1c27 to your computer and use it in GitHub Desktop.
Save snlehton/0fd9b2138f0f513b36119926f9ed1c27 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
public static class ListExtensions
{
public static T GetRandomWeighted<T>(this List<T> list, Func<T, float> selector)
{
T selected = default(T);
float totalWeight = 0;
foreach (var item in list)
{
float weight = selector(item);
if (weight <= 0)
continue;
totalWeight += weight;
float prob = weight / totalWeight;
if (UnityEngine.Random.value < prob)
{
selected = item;
}
}
return selected;
}
}
/*
// get random item with weight
public class Item
{
public GameObject someData;
public float weight;
}
List<Item> items = ...;
Item item = items.GetRandomWeighted(o => o.weight);
...
// get random float with its value as weight
List<float> floats = ...;
float f = floats.GetRandomWeighted(o => o);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment