C#将数组内元素打乱顺序

本文介绍了一个使用泛型类实现数组打乱功能的示例代码,包括构造函数、显示类型的方法、获取原始数组的方法以及获取打乱顺序后的数组的方法。通过实例展示了如何在主函数中调用这些方法并输出结果。

1.泛型类代码

//泛型类
class Item<T>
{
    T[] item;

    //构造函数
    public Item(T[] obj)
    {
        item = new T[obj.Length];
        for (int i = 0; i < obj.Length; i++)
        {
            item[i] = obj[i];
        }
    }

    public Type ShowType() { return typeof(T); } //返回类型
    public T[] GetItems() { return item; } //返回原数组

    //返回打乱顺序后的数组
    public T[] GetDisruptedItems() 
    {
        //生成一个新数组:用于在之上计算和返回
        T[] temp;
        temp = new T[item.Length];
        for (int i = 0; i < temp.Length; i++) { temp[i] = item[i]; }

        //打乱数组中元素顺序
        Random rand = new Random(DateTime.Now.Millisecond);
        for (int i = 0; i < temp.Length; i++)
        {
            int x, y; T t;
            x = rand.Next(0, temp.Length);
            do
            {
                y = rand.Next(0, temp.Length);
            } while (y == x);

            t = temp[x];
            temp[x] = temp[y];
            temp[y] = t;
        }

        return temp;
    }
}

2.Main函数调用

static void Main(string[] args)
{
    int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    //输出数组类型
    Item<int> disrupter = new Item<int>(array);
    Console.WriteLine("数组类型:" + disrupter.ShowType().ToString());

    //输出数组
    Console.Write("原输入数组为:");
    for (int i = 0; i < array.Length; i++)
    {
        Console.Write(array[i].ToString() + ' ');
    }
    Console.WriteLine();

    //输出一个打乱后数组
    int[] disruptedArray = disrupter.GetDisruptedItems();
    Console.Write("打乱后数组为:");
    for (int i = 0; i < disruptedArray.Length; i++)
    {
        Console.Write(disruptedArray[i].ToString() + ' ');
    }
    Console.WriteLine();

    Console.ReadLine();
}

3.运行结果

231719_qjDX_1425762.png

转载于:https://my.oschina.net/Tsybius2014/blog/263405

### 实现数组元素顺序随机打乱 #### Fisher-Yates洗牌算法简介 Fisher-Yates洗牌算法是一种高效的算法,能够确保每个排列出现的概率相等。此算法通过迭代地从未处理的部分选择一个随机元素当前元素交换来工作[^1]。 #### C#实现示例 下面展示的是利用C#语言实现的基于Fisher-Yates算法数组打乱功能: ```csharp using System; public class Program { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; Shuffle(array); foreach(var item in array){ Console.WriteLine(item); } } private static Random rng = new Random(); public static void Shuffle<T>(T[] array) { for (int n = array.Length; n > 1;) { int k = rng.Next(n--); // 随机选一个索引 T temp = array[n]; array[n] = array[k]; array[k] = temp; } } } ``` 这段代码首先初始化了一个整型数组`array`,接着调用了静态方法`Shuffle()`来进行打乱操作。注意这里使用了泛型使得函数可以适用于任何类型的数组。 #### Java实现方式 对于Java而言,同样可以通过引入`Random`类实例化对象来获取伪随机数源,并以此为基础完成类似的逻辑: ```java import java.util.Random; class Solution { private final Random randGen = new Random(); /** Resets the array to its original configuration and return it. */ public int[] reset(int[] nums) { return Arrays.copyOf(nums, nums.length); } /** Returns a random shuffling of the array. */ public int[] shuffle(int[] nums) { for (int i = nums.length - 1; i >= 0; --i) { swapAt(nums, i, this.randGen.nextInt(i + 1)); } return nums; } private void swapAt(int[] A, int i, int j) { if (i != j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } } ``` 在这个例子中,除了实现了基本的打乱外还提供了重置的功能以便于多次测试验证效果[^5]。 #### Python简洁版 Python由于其内置库的支持可以让这个过程更加简单明了: ```python from random import randint def fisher_yates_shuffle(lst): for i in range(len(lst)-1, 0, -1): j = randint(0, i) lst[i], lst[j] = lst[j], lst[i] example_list = ['apple', 'banana', 'cherry'] fisher_yates_shuffle(example_list) print(example_list) ``` 这里的`randint(a,b)`会生成[a,b]区间内的一个随机整数作为新的位置索引来当前正在访问的位置做交换[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值