生成随机不重复的数组

之分享过一个生成随机不重复数组的一个算法,感觉不太完善,有一点缺陷。这里重新分享一个新的。核心代码如下如下:

using System;
using System.Collections;
using System.Collections.Generic;
public class RandomIndex {
    //单实例模式
    private static RandomIndex _instance;
    public static RandomIndex Instance {
        get {
            if (_instance == null) {
                _instance = new RandomIndex ();
            }
            return _instance;
        }
    }
    /// <summary>
    /// 创建一个不重复的随机数组
    /// </summary>
    /// <param name="maxSeedLength">取随机值的最大值</param>
    /// <param name="returnLength">返回元素的个数</param>
    /// <returns></returns>
    public int[] CreateRandomNmber (int maxSeedLength, int returnLength) {
        List<int> list = new List<int> ();
        System.Random rd = new System.Random ();
        for (int i = 0; i < returnLength; i++) {
            int temp = rd.Next (0, maxSeedLength);
            while (list.Contains (temp)) {
                temp = rd.Next (0, maxSeedLength);
            }
            list.Add (temp);
        }
        return list.ToArray ();
    }
}

添加一个测试类如下:

using System;

namespace temp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
           int[] temp=RandomIndex.Instance.CreateRandomNmber(20,5);
           foreach(var i in temp){
               System.Console.WriteLine(i);
           }
        }
    }
}

输出如下所示:


image

更多内容欢迎关注:


这里写图片描述

猜你喜欢

转载自blog.csdn.net/JianZuoGuang/article/details/80766354