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

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值