Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Common/3.3/EnumerableExtensions.cs @ 17226

Last change on this file since 17226 was 17226, checked in by mkommend, 5 years ago

#2521: Merged trunk changes into problem refactoring branch.

File size: 7.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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;
25
26namespace HeuristicLab.Common {
27  public static class EnumerableExtensions {
28    public static T[,] ToMatrix<T>(this IEnumerable<IEnumerable<T>> source) {
29      if (source == null) throw new ArgumentNullException("source");
30      if (!source.Any()) return new T[0, 0];
31
32      int firstDimension = source.Count();
33      int secondDimension = source.First().Count();
34      var result = new T[firstDimension, secondDimension];
35
36      int i = 0;
37      int j = 0;
38      foreach (var row in source) {
39        j = 0;
40        foreach (var element in row) {
41          result[i, j] = element;
42          j++;
43        }
44        if (j != secondDimension) throw new InvalidOperationException("All enumerables must be of the same length.");
45        i++;
46      }
47
48      return result;
49    }
50
51
52    /// <summary>
53    /// Selects all elements in the sequence that are maximal with respect to the given value.
54    /// </summary>
55    /// <remarks>
56    /// Runtime complexity of the operation is O(N).
57    /// </remarks>
58    /// <typeparam name="T">The type of the elements.</typeparam>
59    /// <param name="source">The enumeration in which the items with a maximal value should be found.</param>
60    /// <param name="valueSelector">The function that selects the value to compare.</param>
61    /// <returns>All elements in the enumeration where the selected value is the maximum.</returns>
62    public static IEnumerable<T> MaxItems<T>(this IEnumerable<T> source, Func<T, IComparable> valueSelector) {
63      IEnumerator<T> enumerator = source.GetEnumerator();
64      if (!enumerator.MoveNext()) return Enumerable.Empty<T>();
65      IComparable max = valueSelector(enumerator.Current);
66      var result = new List<T>();
67      result.Add(enumerator.Current);
68
69      while (enumerator.MoveNext()) {
70        T item = enumerator.Current;
71        IComparable comparison = valueSelector(item);
72        if (comparison.CompareTo(max) > 0) {
73          result.Clear();
74          result.Add(item);
75          max = comparison;
76        } else if (comparison.CompareTo(max) == 0) {
77          result.Add(item);
78        }
79      }
80      return result;
81    }
82
83    /// <summary>
84    /// Selects all elements in the sequence that are minimal with respect to the given value.
85    /// </summary>
86    /// <remarks>
87    /// Runtime complexity of the operation is O(N).
88    /// </remarks>
89    /// <typeparam name="T">The type of the elements.</typeparam>
90    /// <param name="source">The enumeration in which items with a minimal value should be found.</param>
91    /// <param name="valueSelector">The function that selects the value.</param>
92    /// <returns>All elements in the enumeration where the selected value is the minimum.</returns>
93    public static IEnumerable<T> MinItems<T>(this IEnumerable<T> source, Func<T, IComparable> valueSelector) {
94      IEnumerator<T> enumerator = source.GetEnumerator();
95      if (!enumerator.MoveNext()) return Enumerable.Empty<T>();
96      IComparable min = valueSelector(enumerator.Current);
97      var result = new List<T>();
98      result.Add(enumerator.Current);
99
100      while (enumerator.MoveNext()) {
101        T item = enumerator.Current;
102        IComparable comparison = valueSelector(item);
103        if (comparison.CompareTo(min) < 0) {
104          result.Clear();
105          result.Add(item);
106          min = comparison;
107        } else if (comparison.CompareTo(min) == 0) {
108          result.Add(item);
109        }
110      }
111      return result;
112    }
113
114    /// <summary>
115    /// Compute the n-ary cartesian product of arbitrarily many sequences: http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
116    /// </summary>
117    /// <typeparam name="T">The type of the elements inside each sequence</typeparam>
118    /// <param name="sequences">The collection of sequences</param>
119    /// <returns>An enumerable sequence of all the possible combinations of elements</returns>
120    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
121      IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
122      return sequences.Where(s => s.Any()).Aggregate(result, (current, s) => (from seq in current from item in s select seq.Concat(new[] { item })));
123    }
124
125    /// <summary>
126    /// Compute all k-combinations of elements from the provided collection.
127    /// <param name="elements">The collection of elements</param>
128    /// <param name="k">The combination group size</param>
129    /// <returns>An enumerable sequence of all the possible k-combinations of elements</returns>
130    /// </summary>
131    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IList<T> elements, int k) {
132      if (k > elements.Count)
133        throw new ArgumentException();
134
135      if (k == 1) {
136        foreach (var element in elements)
137          yield return new[] { element };
138        yield break;
139      }
140
141      int n = elements.Count;
142      var range = Enumerable.Range(0, k).ToArray();
143      var length = BinomialCoefficient(n, k);
144
145      for (int i = 0; i < length; ++i) {
146        yield return range.Select(x => elements[x]).ToArray();
147
148        if (i == length - 1) break;
149        var m = k - 1;
150        var max = n - 1;
151
152        while (range[m] == max) { --m; --max; }
153        range[m]++;
154        for (int j = m + 1; j < k; ++j) {
155          range[j] = range[j - 1] + 1;
156        }
157      }
158    }
159
160    /// <summary>
161    /// This function gets the total number of unique combinations based upon N and K,
162    /// where N is the total number of items and K is the size of the group.
163    /// It calculates the total number of unique combinations C(N, K) = N! / ( K! (N - K)! )
164    /// using the  recursion C(N+1, K+1) = (N+1 / K+1) * C(N, K).
165    /// <remarks>http://blog.plover.com/math/choose.html</remarks>
166    /// <remark>https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula</remark>
167    /// <param name="n">The number of elements</param>
168    /// <param name="k">The size of the group</param>
169    /// <returns>The binomial coefficient C(N, K)</returns>
170    /// </summary>
171    public static long BinomialCoefficient(long n, long k) {
172      if (k > n) return 0;
173      if (k == n) return 1;
174      if (k > n - k)
175        k = n - k;
176
177      // enable explicit overflow checking for very large coefficients
178      checked {
179        long r = 1;
180        for (long d = 1; d <= k; d++) {
181          r *= n--;
182          r /= d;
183        }
184        return r;
185      }
186    }
187  }
188}
Note: See TracBrowser for help on using the repository browser.