2019-12-06 12:06:13 +01:00
|
|
|
using System;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
2021-06-19 18:02:33 +02:00
|
|
|
namespace Jellyfin.Extensions
|
2019-12-06 12:06:13 +01:00
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// Provides <c>Shuffle</c> extensions methods for <see cref="IList{T}" />.
|
|
|
|
/// </summary>
|
|
|
|
public static class ShuffleExtensions
|
|
|
|
{
|
|
|
|
private static readonly Random _rng = new Random();
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Shuffles the items in a list.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="list">The list that should get shuffled.</param>
|
|
|
|
/// <typeparam name="T">The type.</typeparam>
|
|
|
|
public static void Shuffle<T>(this IList<T> list)
|
2020-03-05 00:54:46 +01:00
|
|
|
{
|
|
|
|
list.Shuffle(_rng);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Shuffles the items in a list.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="list">The list that should get shuffled.</param>
|
|
|
|
/// <param name="rng">The random number generator to use.</param>
|
|
|
|
/// <typeparam name="T">The type.</typeparam>
|
|
|
|
public static void Shuffle<T>(this IList<T> list, Random rng)
|
2019-12-06 12:06:13 +01:00
|
|
|
{
|
|
|
|
int n = list.Count;
|
|
|
|
while (n > 1)
|
|
|
|
{
|
2021-01-26 20:28:35 +01:00
|
|
|
int k = rng.Next(n--);
|
2019-12-06 12:06:13 +01:00
|
|
|
T value = list[k];
|
|
|
|
list[k] = list[n];
|
|
|
|
list[n] = value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|