namespace HeuristicLab.Problems.ProgramSynthesis { using System; using System.Collections.Generic; using System.Linq; using HeuristicLab.Core; using HeuristicLab.Random; public static class EnumerableExtensions { public static T RandomWeightedOrDefault(this IEnumerable items, IRandom random, Func weightResolver) { random = random ?? new MersenneTwister(); var totalWeight = items.Sum(weightResolver); // The weight we are after... var itemWeightIndex = random.NextDouble() * totalWeight; var currentWeightIndex = 0d; foreach (var item in items) { currentWeightIndex += weightResolver(item); // If we've hit or passed the weight we are after for this item then it's the one we want.... if (currentWeightIndex >= itemWeightIndex) return item; } return default(T); } } }