Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1614

  • added first version of GRASP+PR algorithm
File size: 4.5 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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Core;
25
26namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment {
27  public static class ExtensionMethods {
28    /// <summary>
29    /// Selects an element from an enumerable randomly with equal probability for each element.
30    /// </summary>
31    /// <typeparam name="T">The type of the items that are to be selected.</typeparam>
32    /// <param name="source">The enumerable that contains the items.</param>
33    /// <param name="random">The random number generator, its NextDouble() method must return a value in the range [0;1).</param>
34    /// <param name="selected">True if an element was selected, false otherwise (mainly because of an empty sequence).</param>
35    /// <returns>The selected item.</returns>
36    public static T SelectRandomOrDefault<T>(this IEnumerable<T> source, IRandom random, out bool selected) {
37      int counter = 1;
38      selected = false;
39      T selectedItem = default(T);
40      foreach (T item in source) {
41        if (random.NextDouble() < 1.0 / counter) {
42          selectedItem = item;
43          selected = true;
44        }
45      }
46      return selectedItem;
47    }
48
49    /// <summary>
50    /// Shuffles an enumerable and returns an new enumerable according to the Fisher-Yates shuffle.
51    /// </summary>
52    /// <remarks>
53    /// Source code taken from http://stackoverflow.com/questions/1287567/c-is-using-random-and-orderby-a-good-shuffle-algorithm.
54    /// Note that this is an online shuffle, but the source enumerable is transformed into an array.
55    /// </remarks>
56    /// <typeparam name="T">The type of the items that are to be shuffled.</typeparam>
57    /// <param name="source">The enumerable that contains the items.</param>
58    /// <param name="random">The random number generator, its Next(int) method must deliver uniformly distributed random numbers.</param>
59    /// <returns>An enumerable with the elements shuffled.</returns>
60    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, IRandom random) {
61      T[] elements = source.ToArray();
62      // Note i > 0 to avoid final pointless iteration
63      for (int i = elements.Length - 1; i > 0; i--) {
64        // Swap element "i" with a random earlier element it (or itself)
65        int swapIndex = random.Next(i + 1);
66        yield return elements[swapIndex];
67        elements[swapIndex] = elements[i];
68        // we don't actually perform the swap, we can forget about the
69        // swapped element because we already returned it.
70      }
71
72      // there is one item remaining that was not returned - we return it now
73      yield return elements[0];
74    }
75
76    /// <summary>
77    /// Walks an operator graph in that it jumps from one operator to all its operator parameters and yields each operator it touches.
78    /// Cycles are detected and not walked twice.
79    /// </summary>
80    /// <param name="initial">The operator where the walk starts (is also yielded).</param>
81    /// <returns>An enumeration of all the operators that could be found.</returns>
82    public static IEnumerable<IOperator> Walk(this IOperator initial) {
83      var open = new Stack<IOperator>();
84      var visited = new HashSet<IOperator>();
85      open.Push(initial);
86
87      while (open.Any()) {
88        IOperator current = open.Pop();
89        if (visited.Contains(current)) continue;
90        visited.Add(current);
91
92        foreach (var parameter in current.Parameters.OfType<IValueParameter>()) {
93          if (typeof(IOperator).IsAssignableFrom(parameter.DataType)) {
94            if (parameter.Value != null)
95              open.Push((IOperator)parameter.Value);
96          }
97        }
98
99        yield return current;
100      }
101    }
102
103  }
104}
Note: See TracBrowser for help on using the repository browser.