Last change
on this file since 15694 was
15273,
checked in by pkimmesw, 7 years ago
|
#2665 Started Plush Encoding, Added Zero Error Individual Count Analyzer
|
File size:
945 bytes
|
Line | |
---|
1 | namespace HeuristicLab.Problems.ProgramSynthesis.Base.Extensions {
|
---|
2 | using System;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | using System.Linq;
|
---|
5 |
|
---|
6 | using HeuristicLab.Core;
|
---|
7 | using HeuristicLab.Random;
|
---|
8 |
|
---|
9 | public static class EnumerableExtensions {
|
---|
10 | public static T RandomWeightedOrDefault<T>(this IEnumerable<T> items, IRandom random, Func<T, double> weightResolver) {
|
---|
11 | random = random ?? new MersenneTwister();
|
---|
12 | var totalWeight = items.Sum(weightResolver);
|
---|
13 |
|
---|
14 | // The weight we are after...
|
---|
15 | var itemWeightIndex = random.NextDouble() * totalWeight;
|
---|
16 | var currentWeightIndex = 0d;
|
---|
17 |
|
---|
18 | foreach (var item in items) {
|
---|
19 | currentWeightIndex += weightResolver(item);
|
---|
20 |
|
---|
21 | // If we've hit or passed the weight we are after for this item then it's the one we want....
|
---|
22 | if (currentWeightIndex >= itemWeightIndex)
|
---|
23 | return item;
|
---|
24 | }
|
---|
25 |
|
---|
26 | return default(T);
|
---|
27 | }
|
---|
28 | }
|
---|
29 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.