// Copyright (C) 2019-2021 gamevanilla. All rights reserved.
// This code can only be used under the standard Unity Asset Store End User License Agreement,
// a copy of which is available at http://unity3d.com/company/legal/as_terms.
using System;
using System.Collections.Generic;
namespace CCGKit
{
/// <summary>
/// Utility extension method to shuffle NativeLists.
/// </summary>
public static class ListShuffle
{
private static readonly Random Rng = new Random();
public static void Shuffle<T>(this List<T> list)
{
var n = list.Count;
while (n --> 1)
{
var k = Rng.Next(n + 1);
var value = list[k];
list[k] = list[n];
list[n] = value;
}
}
public static void Shuffle<T>(this List<T> list, Random rng)
{
var n = list.Count;
while (n --> 1)
{
var k = rng.Next(n + 1);
var value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
使用方法:
deck.Shuffle();

本文介绍了C#中一个实用的扩展方法,用于对NativeLists进行随机洗牌操作。提供了两种洗牌方式,一种使用内置的Random类,另一种允许传入自定义的随机数生成器。这个扩展方法对于需要随机排列元素的场景非常有用,例如在游戏开发或算法测试中。
1793

被折叠的 条评论
为什么被折叠?



