Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Analysis.FitnessLandscape/3.3/Analysis/EnumerableExtensions.cs @ 17514

Last change on this file since 17514 was 13583, checked in by abeham, 9 years ago

#2457:

  • Added stripped-down version of FLA branch
  • Added appropriate calculators
  • Fixed detecting maximization in RLD view
File size: 2.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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;
24
25namespace HeuristicLab.Analysis.FitnessLandscape {
26
27  public static class Utils {
28
29    public static IEnumerable<TResult> Delta<T, TResult>(this IEnumerable<T> values, Func<T, T, TResult> f) {
30      var it = values.GetEnumerator();
31      T last = default(T);
32      if (it.MoveNext())
33        last = it.Current;
34      while (it.MoveNext()) {
35        yield return f(last, it.Current);
36        last = it.Current;
37      }
38    }
39
40    public static IEnumerable<IEnumerable<TSource>> GroupConsecutive<TSource, TKey>(
41        this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) {
42      if (source == null) throw new ArgumentNullException("source");
43      if (keySelector == null) throw new ArgumentNullException("keySelector");
44
45      var comparer = EqualityComparer<TKey>.Default;
46      var grouped = new List<TSource>();
47      using (var iter = source.GetEnumerator()) {
48        if (!iter.MoveNext()) yield break;
49        grouped.Add(iter.Current);
50        var last = iter.Current;
51        while (iter.MoveNext()) {
52          if (!comparer.Equals(keySelector(iter.Current), keySelector(last))) {
53            yield return grouped.AsReadOnly();
54            grouped = new List<TSource>();
55          }
56          grouped.Add(iter.Current);
57          last = iter.Current;
58        }
59        yield return grouped.AsReadOnly();
60      }
61    }
62  }
63}
Note: See TracBrowser for help on using the repository browser.