Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12316 was 12316, checked in by mkommend, 9 years ago

#2320: Implemented symbolic expression tree encoding.

File size: 2.4 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
29  //This class should not be used anymore. Use HeuristicLab.Random.RandomEnumberable instead
30  //This could not be fixed right now, because the algorithm behavior would be modified => version increment
31  internal static class EnumerableExtensions {
32    internal static T SelectRandom<T>(this IEnumerable<T> xs, IRandom random) {
33      var list = xs as IList<T>;
34      if (list != null) {
35        return list[random.Next(list.Count)];
36      } else {
37        list = xs.ToList();
38        return list[random.Next(list.Count)];
39      }
40    }
41    internal static T SelectRandom<T>(this IEnumerable<T> xs, IEnumerable<double> weights, IRandom random) {
42      var list = xs as IList<T>;
43      var weightsList = weights as IList<double>;
44      if (list == null) {
45        list = xs.ToList();
46      }
47      if (weightsList == null) {
48        weightsList = weights.ToList();
49      }
50      if (list.Count != weightsList.Count) throw new ArgumentException("Number of elements in enumerations doesn't match.");
51      if (list.Count == 0) throw new ArgumentException("Enumeration is empty", "xs");
52
53      double sum = weightsList.Sum();
54      double r = random.NextDouble() * sum;
55      double agg = 0;
56      for (int i = 0; i < list.Count; i++) {
57        agg += weightsList[i];
58        if (agg > r) return list[i];
59      }
60      // should never happen
61      throw new InvalidOperationException();
62    }
63  }
64}
Note: See TracBrowser for help on using the repository browser.