mirror of
https://gitlab.com/MaddoScientisto/cirnogodot.git
synced 2026-06-01 10:35:34 +00:00
Fisher-Yates shuffle
This commit is contained in:
parent
60f755aca5
commit
aa838aeda1
6 changed files with 176 additions and 7 deletions
45
Scripts/Utils/ShuffleExtensions.cs
Normal file
45
Scripts/Utils/ShuffleExtensions.cs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Godot;
|
||||
|
||||
namespace Cirno.Scripts.Utils;
|
||||
|
||||
public static class ShuffleExtensions
|
||||
{
|
||||
//private static Random rng = new Random();
|
||||
|
||||
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, int? desiredLength = null)
|
||||
{
|
||||
if (source == null) throw new ArgumentNullException(nameof(source));
|
||||
|
||||
var list = source.ToList();
|
||||
int originalCount = list.Count;
|
||||
|
||||
if (originalCount == 0) yield break;
|
||||
|
||||
// Repeat elements to meet the desired length
|
||||
if (desiredLength.HasValue && desiredLength > originalCount)
|
||||
{
|
||||
int countToAdd = desiredLength.Value - originalCount;
|
||||
for (int i = 0; i < countToAdd; i++)
|
||||
{
|
||||
list.Add(list[i % originalCount]);
|
||||
}
|
||||
}
|
||||
|
||||
// Fisher-Yates shuffle
|
||||
for (int i = list.Count - 1; i > 0; i--)
|
||||
{
|
||||
//int j = rng.Next(i + 1);
|
||||
int j = GD.RandRange(0, i);
|
||||
(list[i], list[j]) = (list[j], list[i]);
|
||||
}
|
||||
|
||||
// Return only up to desired length if specified
|
||||
foreach (var item in list.Take(desiredLength ?? list.Count))
|
||||
{
|
||||
yield return item;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue