Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections.Generic;
- using System.Linq;
- public class RandomUtility {
- public interface Weighted {
- float getWeight();
- }
- public static T pickWeighted<T>(IList<T> arr, IList<float> weights) {
- float total = weights.Sum ();
- float pick = Random.Range (0.0f, total);
- int idx = 0;
- while (idx < weights.Count-1 && weights[idx] < pick) pick -= weights[idx++];
- return arr[idx];
- }
- public static T pickWeighted<T>(IList<T> arr) where T:RandomUtility.Weighted {
- float total = 0.0f;
- foreach (T obj in arr) total += obj.getWeight();
- float pick = Random.Range (0.0f, total);
- int idx = 0;
- while (idx < arr.Count-1 && arr[idx].getWeight () < pick) pick -= arr[idx++].getWeight();
- return arr[idx];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement