关闭

一返回指定范围的不重复随机数类

374人阅读 评论(0) 收藏 举报

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;

/// <summary>
/// Summary description for RandomCls
/// </summary>
public class RandomCls : Random
{

    private ArrayList element = null;
    private int min;
    private int max;

    public RandomCls(int min, int max)
    {
        this.min = min;
        this.max = max;
        element = new ArrayList();
    }

    public void add(int index)
    {
        if (!element.Contains(index))
            element.Add(index);
    }

    public object this[int index]
    {
        get { return element[index]; }
        set { element[index] = value; }
    }

    public override int Next()
    {
        return base.Next(this.min, this.max);
    }

    public int getDifferenceRandomNumber()
    {
        int number ;
        do
            number = this.Next(min, max);
        while (element.Contains(number) && element.Count < max - 1);
        add(number);
        return number;
    }

    public int[] getArrayRandom()
    {
        int[] temp = new int[max - min];
        for (int i = 0; i < max - min; i++)
        {
            temp[i] = getDifferenceRandomNumber();
        }
        return temp;
    }
}

 

调用:

        int[] array = new int[100];
        RandomCls randomUsr = new RandomCls(1, 100);
        array = randomUsr.getArrayRandom();


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:163225次
    • 积分:2390
    • 等级:
    • 排名:第16093名
    • 原创:59篇
    • 转载:64篇
    • 译文:0篇
    • 评论:11条
    文章分类
    最新评论