Advertisement
Guest User

Weighted Random

a guest
Oct 9th, 2014
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.76 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public class RandomUtility {
  6.    
  7.     public interface Weighted {
  8.         float getWeight();
  9.     }
  10.    
  11.     public static T pickWeighted<T>(IList<T> arr, IList<float> weights) {
  12.         float total = weights.Sum ();
  13.         float pick = Random.Range (0.0f, total);
  14.         int idx = 0;
  15.         while (idx < weights.Count-1 && weights[idx] < pick) pick -= weights[idx++];
  16.         return arr[idx];
  17.     }
  18.    
  19.     public static T pickWeighted<T>(IList<T> arr) where T:RandomUtility.Weighted {
  20.         float total = 0.0f;
  21.         foreach (T obj in arr) total += obj.getWeight();
  22.         float pick = Random.Range (0.0f, total);
  23.         int idx = 0;
  24.         while (idx < arr.Count-1 && arr[idx].getWeight () < pick) pick -= arr[idx++].getWeight();
  25.         return arr[idx];
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement