Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Common/3.3/ExtensionMethods.cs @ 7415

Last change on this file since 7415 was 7415, checked in by abeham, 12 years ago

#1614: improved results output of GQAP

File size: 8.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Problems.GeneralizedQuadraticAssignment.Common {
28  public static class ExtensionMethods {
29
30    /// <summary>
31    /// Selects an element from an enumerable randomly with equal probability for each element. If the sequence is empty, selected will be false and default(T) will be returned.
32    /// </summary>
33    /// <typeparam name="T">The type of the items that are to be selected.</typeparam>
34    /// <param name="source">The enumerable that contains the items.</param>
35    /// <param name="random">The random number generator, its NextDouble() method must return a value in the range [0;1).</param>
36    /// <param name="selected">True if an element was selected, false otherwise (only because of an empty sequence).</param>
37    /// <returns>The selected item.</returns>
38    public static T ChooseRandomOrDefault<T>(this IEnumerable<T> source, IRandom random, out bool selected) {
39      if (source == null) throw new ArgumentNullException("SelectRandomOrDefault: source is null");
40      uint counter = 1;
41      selected = false;
42      T selectedItem = default(T);
43      foreach (T item in source) {
44        if (counter * random.NextDouble() < 1.0) { // use multiplication instead of division
45          selectedItem = item;
46          selected = true;
47        }
48        counter++;
49      }
50      return selectedItem;
51    }
52
53    /// <summary>
54    /// Selects an element from an enumerable randomly with equal probability for each element.
55    /// </summary>
56    /// <typeparam name="T">The type of the items that are to be selected.</typeparam>
57    /// <param name="source">The enumerable that contains the items.</param>
58    /// <param name="random">The random number generator, its NextDouble() method must return a value in the range [0;1).</param>
59    /// <returns>The selected item.</returns>
60    public static T ChooseRandom<T>(this IEnumerable<T> source, IRandom random) {
61      if (source == null) throw new ArgumentNullException("SelectRandom: source is null");
62      if (!source.Any()) throw new ArgumentException("SelectRandom: sequence is empty.");
63      uint counter = 1;
64      T selectedItem = default(T);
65      foreach (T item in source) {
66        if (counter * random.NextDouble() < 1.0) // use multiplication instead of division
67          selectedItem = item;
68        counter++;
69      }
70      return selectedItem;
71    }
72
73    /// <summary>
74    /// Shuffles an enumerable and returns an new enumerable according to the Fisher-Yates shuffle.
75    /// </summary>
76    /// <remarks>
77    /// Source code taken from http://stackoverflow.com/questions/1287567/c-is-using-random-and-orderby-a-good-shuffle-algorithm.
78    /// Note that this is an online shuffle, but the source enumerable is transformed into an array.
79    /// </remarks>
80    /// <typeparam name="T">The type of the items that are to be shuffled.</typeparam>
81    /// <param name="source">The enumerable that contains the items.</param>
82    /// <param name="random">The random number generator, its Next(int) method must deliver uniformly distributed random numbers.</param>
83    /// <returns>An enumerable with the elements shuffled.</returns>
84    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, IRandom random) {
85      T[] elements = source.ToArray();
86      // Note i > 0 to avoid final pointless iteration
87      for (int i = elements.Length - 1; i > 0; i--) {
88        // Swap element "i" with a random earlier element it (or itself)
89        int swapIndex = random.Next(i + 1);
90        yield return elements[swapIndex];
91        elements[swapIndex] = elements[i];
92        // we don't actually perform the swap, we can forget about the
93        // swapped element because we already returned it.
94      }
95
96      // there is one item remaining that was not returned - we return it now
97      yield return elements[0];
98    }
99
100    /// <summary>
101    /// Selects the first element in the sequence where the selected key is the maximum.
102    /// </summary>
103    /// <remarks>
104    /// Runtime complexity of the operation is O(N).
105    /// </remarks>
106    /// <typeparam name="T">The type of the elements.</typeparam>
107    /// <typeparam name="TComparable">The selected key (needs to be an IComparable).</typeparam>
108    /// <param name="source">The enumeration in which the maximum item should be found.</param>
109    /// <param name="keySelector">The function that selects the key.</param>
110    /// <returns>The element in the enumeration where the selected key is the maximum.</returns>
111    public static T SelectMax<T, TComparable>(this IEnumerable<T> source, Func<T, TComparable> keySelector) where TComparable : IComparable {
112      IEnumerator<T> enumerator = source.GetEnumerator();
113      if (!enumerator.MoveNext()) throw new InvalidOperationException("Sequence is empty!");
114      T result = enumerator.Current;
115      TComparable max = keySelector(result);
116      while (enumerator.MoveNext()) {
117        T item = enumerator.Current;
118        TComparable comparison = keySelector(item);
119        if (comparison.CompareTo(max) > 0) {
120          result = item;
121          max = comparison;
122        }
123      }
124      return result;
125    }
126
127    /// <summary>
128    /// Selects the first element in the sequence where the selected key is the minimum.
129    /// </summary>
130    /// <remarks>
131    /// Runtime complexity of the operation is O(N).
132    /// </remarks>
133    /// <typeparam name="T">The type of the elements.</typeparam>
134    /// <typeparam name="TComparable">The selected key (needs to be an IComparable).</typeparam>
135    /// <param name="source">The enumeration in which the minimum item should be found.</param>
136    /// <param name="keySelector">The function that selects the key.</param>
137    /// <returns>The element in the enumeration where the selected key is the minimum.</returns>
138    public static T SelectMin<T, TComparable>(this IEnumerable<T> source, Func<T, TComparable> keySelector) where TComparable : IComparable {
139      IEnumerator<T> enumerator = source.GetEnumerator();
140      if (!enumerator.MoveNext()) throw new InvalidOperationException("Sequence is empty!");
141      T result = enumerator.Current;
142      TComparable min = keySelector(result);
143      while (enumerator.MoveNext()) {
144        T item = enumerator.Current;
145        TComparable comparison = keySelector(item);
146        if (comparison.CompareTo(min) < 0) {
147          result = item;
148          min = comparison;
149        }
150      }
151      return result;
152    }
153
154    /// <summary>
155    /// Walks an operator graph in that it jumps from one operator to all its operator parameters and yields each operator it touches.
156    /// Cycles are detected and not walked twice.
157    /// </summary>
158    /// <param name="initial">The operator where the walk starts (is also yielded).</param>
159    /// <returns>An enumeration of all the operators that could be found.</returns>
160    public static IEnumerable<IOperator> Walk(this IOperator initial) {
161      var open = new Stack<IOperator>();
162      var visited = new HashSet<IOperator>();
163      open.Push(initial);
164
165      while (open.Any()) {
166        IOperator current = open.Pop();
167        if (visited.Contains(current)) continue;
168        visited.Add(current);
169
170        foreach (var parameter in current.Parameters.OfType<IValueParameter>()) {
171          if (typeof(IOperator).IsAssignableFrom(parameter.DataType)) {
172            if (parameter.Value != null)
173              open.Push((IOperator)parameter.Value);
174          }
175        }
176
177        yield return current;
178      }
179    }
180
181  }
182}
Note: See TracBrowser for help on using the repository browser.