22 Star 152 Fork 69

编程语言算法集/C-Sharp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
FisherYatesShuffler.cs 1.00 KB
一键复制 编辑 原始数据 按行查看 历史
namespace Algorithms.Shufflers;
/// <summary>
/// Fisher-Yates shuffle is a simple shuffling algorithm,
/// which is usually used to shuffle a deck of cards.
/// </summary>
/// <typeparam name="T">Type array input.</typeparam>
public class FisherYatesShuffler<T> : IShuffler<T>
{
/// <summary>
/// Shuffles input array using Fisher-Yates algorithm.
/// The algorithm starts shuffling from the last element
/// and swap elements one by one. We use random index to
/// choose element we use in swap operation.
/// </summary>
/// <param name="array">Array to shuffle.</param>
/// <param name="seed">Random generator seed. Used to repeat the shuffle.</param>
public void Shuffle(T[] array, int? seed = null)
{
var random = seed is null ? new Random() : new Random(seed.Value);
for (var i = array.Length - 1; i > 0; i--)
{
var j = random.Next(0, i + 1);
(array[i], array[j]) = (array[j], array[i]);
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/TheAlgorithms/C-Sharp.git
git@gitee.com:TheAlgorithms/C-Sharp.git
TheAlgorithms
C-Sharp
C-Sharp
master

搜索帮助