Last active
February 2, 2019 14:50
-
-
Save tra38/560c300396447820a99a2be53d8afcc3 to your computer and use it in GitHub Desktop.
A C# Shuffler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright 2019 Tariq Ali | |
Licensed under the Apache License, Version 2.0 (the "License"); | |
you may not use this file except in compliance with the License. | |
You may obtain a copy of the License at | |
http://www.apache.org/licenses/LICENSE-2.0 | |
Unless required by applicable law or agreed to in writing, software | |
distributed under the License is distributed on an "AS IS" BASIS, | |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
See the License for the specific language governing permissions and | |
limitations under the License. | |
*/ | |
using System; | |
using System.Collections.Generic; | |
public static class Generator | |
{ | |
static Random _random = new Random(); | |
//https://www.dotnetperls.com/fisher-yates-shuffle | |
public static List<T> Shuffle<T>(List<T> list) | |
{ | |
int n = list.Count; | |
for (int i = 0; i < n; i++) | |
{ | |
int r = i + _random.Next(n - i); | |
T t = list[r]; | |
list[r] = list[i]; | |
list[i] = t; | |
} | |
return list; | |
} | |
public static T Random<T>(List<T> list) | |
{ | |
var index = _random.Next(list.Count); | |
return list[index]; | |
} | |
public static Func<T> GenerateRule<T>(List<T> inputList) | |
{ | |
return () => Random(inputList); | |
} | |
public static Func<T> GenerateUniqueRule<T>(List<T> inputList) | |
{ | |
IEnumerable<T> shuffledList = Shuffle(inputList); | |
var enumerator = shuffledList.GetEnumerator(); | |
Func<T> func = () => | |
{ | |
if (enumerator.MoveNext()) | |
{ | |
//do nothing | |
} | |
else | |
{ | |
enumerator.Reset(); | |
enumerator.MoveNext(); | |
} | |
return enumerator.Current; | |
}; | |
return func; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment