Last change
on this file since 14908 was
14897,
checked in by pkimmesw, 7 years ago
|
#2665 Dynamic ErcValues, Separate Push from BenchmarkSuite Push
|
File size:
903 bytes
|
Line | |
---|
1 | using System.Collections.Generic;
|
---|
2 | using System.Linq;
|
---|
3 |
|
---|
4 | namespace HeuristicLab.Problems.ProgramSynthesis.Base.Weighted {
|
---|
5 | using HeuristicLab.Core;
|
---|
6 | using HeuristicLab.Random;
|
---|
7 |
|
---|
8 | public static class WeightedExtensions {
|
---|
9 | public static T RandomWeightedOrDefault<T>(this IEnumerable<T> items, IRandom random = null) where T : IWeighted {
|
---|
10 | random = random ?? new MersenneTwister();
|
---|
11 | var totalWeight = items.Sum(x => x.Weight);
|
---|
12 | // The weight we are after...
|
---|
13 | var itemWeightIndex = random.NextDouble() * totalWeight;
|
---|
14 | var currentWeightIndex = 0d;
|
---|
15 |
|
---|
16 | foreach (var item in items) {
|
---|
17 | currentWeightIndex += item.Weight;
|
---|
18 |
|
---|
19 | // If we've hit or passed the weight we are after for this item then it's the one we want....
|
---|
20 | if (currentWeightIndex >= itemWeightIndex)
|
---|
21 | return item;
|
---|
22 | }
|
---|
23 |
|
---|
24 | return default(T);
|
---|
25 | }
|
---|
26 | }
|
---|
27 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.