Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/EnumerableExtensions.cs @ 12208

Last change on this file since 12208 was 12208, checked in by bburlacu, 9 years ago

#1772: Merged trunk and worked on the graph view.

File size: 2.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Core;
26
27namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
28  public static class EnumerableExtensions {
29    public static T SelectRandom<T>(this IEnumerable<T> xs, IRandom random) {
30      var list = xs as IList<T>;
31      if (list != null) {
32        return list[random.Next(list.Count)];
33      } else {
34        list = xs.ToList();
35        return list[random.Next(list.Count)];
36      }
37    }
38    public static T SelectRandom<T>(this IEnumerable<T> xs, IEnumerable<double> weights, IRandom random) {
39      var list = xs as IList<T>;
40      var weightsList = weights as IList<double>;
41      if (list == null) {
42        list = xs.ToList();
43      }
44      if (weightsList == null) {
45        weightsList = weights.ToList();
46      }
47      if (list.Count != weightsList.Count) throw new ArgumentException("Number of elements in enumerations doesn't match.");
48      if (list.Count == 0) throw new ArgumentException("Enumeration is empty", "xs");
49
50      double sum = weightsList.Sum();
51      double r = random.NextDouble() * sum;
52      double agg = 0;
53      for (int i = 0; i < list.Count; i++) {
54        agg += weightsList[i];
55        if (agg > r) return list[i];
56      }
57      return list[random.Next(list.Count)];
58    }
59  }
60}
Note: See TracBrowser for help on using the repository browser.