Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Random/3.3/ListExtensions.cs @ 15787

Last change on this file since 15787 was 15584, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers on stable

File size: 2.1 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#endregion
23
24using System.Collections.Generic;
25using HeuristicLab.Core;
26
27namespace HeuristicLab.Random {
28  public static class ListExtensions {
29    public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB) {
30      T tmp = list[indexA];
31      list[indexA] = list[indexB];
32      list[indexB] = tmp;
33      return list;
34    }
35
36    public static IList<T> ShuffleInPlace<T>(this IList<T> list, IRandom random) {
37      return list.ShuffleInPlace(random, 0, list.Count - 1);
38    }
39    public static IList<T> ShuffleInPlace<T>(this IList<T> list, IRandom random, int maxIndex) {
40      return list.ShuffleInPlace(random, 0, maxIndex);
41    }
42    public static IList<T> ShuffleInPlace<T>(this IList<T> list, IRandom random, int minIndex, int maxIndex) {
43      for (int i = maxIndex; i > minIndex; i--) {
44        int swapIndex = random.Next(minIndex, i + 1);
45        list.Swap(i, swapIndex);
46      }
47      return list;
48    }
49
50    public static IEnumerable<T> ShuffleList<T>(this IList<T> source, IRandom random) {
51      for (int i = source.Count - 1; i > 0; i--) {
52        // Swap element "i" with a random earlier element (including itself)
53        int swapIndex = random.Next(i + 1);
54        source.Swap(i, swapIndex);
55        yield return source[i];
56      }
57      yield return source[0];
58    }
59  }
60}
Note: See TracBrowser for help on using the repository browser.