using UnityEngine;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// From http://stackoverflow.com/questions/56692/random-weighted-choice
/// </summary>
public class WeightedBag {

    private static System.Random rand = new System.Random();

	public static T RandomElementByWeight<T>(IEnumerable<T> sequence, Func<T, float> weightSelector) {
		float totalWeight = sequence.Sum(weightSelector);

		float itemWeightIndex =  (float)rand.NextDouble() * totalWeight;
		float currentWeightIndex = 0;
		
		foreach(var item in from weightedItem in sequence select new { Value = weightedItem, Weight = weightSelector(weightedItem) }) {
			currentWeightIndex += item.Weight;

            if (currentWeightIndex >= itemWeightIndex)
            {
                //Debug.Log("RandomElementByWeight chose element with cweight + " + currentWeightIndex + " having weight " + item.Weight + " out of total " + totalWeight);
                return item.Value;
            }
			
		}
		
		return default(T);
		
	}

}
