Last active
June 10, 2017 19:58
-
-
Save snlehton/0fd9b2138f0f513b36119926f9ed1c27 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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