Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13365 was 12005, checked in by abeham, 10 years ago

#2174, #2282: merged revisions r11961,r11963,r11967,r11970,r11971,r11982,r11984,r11998,r12001,r12002,r12003,r12004,r11939,r11945,r11956,r11958,r11959,r11960,r11983,r11987,r11988,r11990,r11993,r11994,r11996,r11999,r12000 to stable

File size: 2.1 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2015 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.