Shuffling stuff larger than 256 will work properly now. Thanks to Joe4evr for finding the bug

This commit is contained in:
Master Kwoth 2016-05-01 18:13:12 +02:00
parent 6da4c3db11
commit e17a320301

View File

@ -138,14 +138,21 @@ namespace NadekoBot.Extensions
/// <param name="list"></param> /// <param name="list"></param>
public static void Shuffle<T>(this IList<T> list) public static void Shuffle<T>(this IList<T> list)
{ {
// Thanks to @Joe4Evr for finding a bug in the old version of the shuffle
var provider = new RNGCryptoServiceProvider(); var provider = new RNGCryptoServiceProvider();
var n = list.Count; var n = list.Count;
while (n > 1) while (n > 1)
{ {
var box = new byte[1]; var box = new byte[(n / Byte.MaxValue) + 1];
do provider.GetBytes(box); int boxSum;
while (!(box[0] < n * (byte.MaxValue / n))); do
var k = (box[0] % n); {
provider.GetBytes(box);
boxSum = box.Sum(b => b);
}
while (!(boxSum < n * ((Byte.MaxValue * box.Length) / n)));
var k = (boxSum % n);
n--; n--;
var value = list[k]; var value = list[k];
list[k] = list[n]; list[k] = list[n];