namespace PCL.Core.Utils; using System; using System.Collections.Generic; using System.Linq; /// /// 提供随机数和集合随机操作的实用方法。 /// public static class RandomUtils { private static readonly Random _SharedRandom = Random.Shared; /// /// 从集合中随机选择一个元素。 /// /// 集合元素类型。 /// 要从中选择元素的集合。 /// 随机选择的元素。 /// 为 null 时抛出。 /// 为空时抛出。 public static T PickRandom(ICollection collection) { if (collection.Count == 0) throw new ArgumentException("集合不能为空", nameof(collection)); var index = _SharedRandom.Next(collection.Count); if (collection is IList list) return list[index]; return collection.Skip(index).First(); } /// /// 生成指定范围内的随机整数(包含 min 和 max)。 /// /// 范围下限(包含)。 /// 范围上限(包含)。 /// 随机整数,范围为 [min, max]。 /// 大于 时抛出。 public static int NextInt(int min, int max) { return min > max ? throw new ArgumentOutOfRangeException(nameof(min), "最小值不能大于最大值") : _SharedRandom.Next(min, max + 1); } /// /// 随机打乱列表的元素,返回新列表。 /// /// 列表元素类型。 /// 要打乱的列表。 /// 包含随机顺序元素的新列表。 /// 为 null 时抛出。 public static List Shuffle(IList list) { var result = new List(list); var n = result.Count; for (var i = n - 1; i > 0; i--) { var j = _SharedRandom.Next(0, i + 1); (result[i], result[j]) = (result[j], result[i]); } return result; } /// /// 原地随机打乱列表的元素。 /// /// 列表元素类型。 /// 要打乱的列表。 /// 为 null 时抛出。 public static void ShuffleInPlace(IList list) { var n = list.Count; for (var i = n - 1; i > 0; i--) { var j = _SharedRandom.Next(0, i + 1); (list[i], list[j]) = (list[j], list[i]); } } }