2016-07-09 22:30:12 +00:00
|
|
|
|
using System;
|
2020-01-26 05:49:52 +00:00
|
|
|
|
using System.Threading;
|
2016-07-09 22:30:12 +00:00
|
|
|
|
|
2017-01-08 07:54:09 +00:00
|
|
|
|
namespace PKHeX.Core
|
2016-07-09 22:30:12 +00:00
|
|
|
|
{
|
2018-05-12 19:28:48 +00:00
|
|
|
|
public static partial class Util
|
2016-07-09 22:30:12 +00:00
|
|
|
|
{
|
2020-01-26 05:49:52 +00:00
|
|
|
|
// Multithread safe rand, ha
|
|
|
|
|
public static Random Rand => _local.Value;
|
2022-03-06 20:23:11 +00:00
|
|
|
|
private static int randomSeed = Environment.TickCount;
|
2018-07-29 20:27:48 +00:00
|
|
|
|
|
2022-03-06 20:23:11 +00:00
|
|
|
|
private static readonly ThreadLocal<Random> _local = new(() =>
|
|
|
|
|
{
|
|
|
|
|
// threads should never really step on each other when starting, but we'll play it safe.
|
|
|
|
|
var seed = Interlocked.Increment(ref randomSeed);
|
|
|
|
|
var mix = (0x41C64E6D * seed) + 0x00006073; // why not
|
|
|
|
|
return new Random(mix);
|
|
|
|
|
});
|
2020-01-26 05:49:52 +00:00
|
|
|
|
|
|
|
|
|
public static uint Rand32() => Rand32(Rand);
|
|
|
|
|
public static uint Rand32(Random rnd) => (uint)rnd.Next(1 << 30) << 2 | (uint)rnd.Next(1 << 2);
|
2017-12-15 04:58:55 +00:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Shuffles the order of items within a collection of items.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <typeparam name="T">Item type</typeparam>
|
|
|
|
|
/// <param name="items">Item collection</param>
|
2022-01-03 05:35:59 +00:00
|
|
|
|
public static void Shuffle<T>(Span<T> items) => Shuffle(items, 0, items.Length, Rand);
|
2019-06-09 02:56:11 +00:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Shuffles the order of items within a collection of items.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <typeparam name="T">Item type</typeparam>
|
|
|
|
|
/// <param name="items">Item collection</param>
|
|
|
|
|
/// <param name="start">Starting position</param>
|
|
|
|
|
/// <param name="end">Ending position</param>
|
2020-01-26 05:49:52 +00:00
|
|
|
|
/// <param name="rnd">RNG object to use</param>
|
2022-01-03 05:35:59 +00:00
|
|
|
|
public static void Shuffle<T>(Span<T> items, int start, int end, Random rnd)
|
2016-07-09 22:30:12 +00:00
|
|
|
|
{
|
2019-06-09 02:56:11 +00:00
|
|
|
|
for (int i = start; i < end; i++)
|
2016-07-09 22:30:12 +00:00
|
|
|
|
{
|
2020-01-26 05:49:52 +00:00
|
|
|
|
int index = i + rnd.Next(end - i);
|
2021-08-20 20:42:25 +00:00
|
|
|
|
(items[index], items[i]) = (items[i], items[index]);
|
2016-07-09 22:30:12 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|