Last change
on this file since 18242 was
15771,
checked in by bburlacu, 7 years ago
|
#2895: Add solution skeleton for PushGP with genealogy analysis.
|
File size:
928 bytes
|
Line | |
---|
1 | namespace HeuristicLab.Problems.ProgramSynthesis { |
---|
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.