现在的位置: 首页 > 综合 > 正文

C#下面产生不重复的随机数字

2012年06月13日 ⁄ 综合 ⁄ 共 566字 ⁄ 字号 评论关闭

本人近来面试碰到一题:产生100个不重复的随机数,解法如下

 

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList array = MyArray.GetArray(10);
        foreach (int i in array)
        {
            Console.WriteLine(i);
        }
    }
}
class MyArray
{
    public static ArrayList GetArray(int length)
    {
        ArrayList myList = new ArrayList();
        Random rnd=new Random ();
        while (myList.Count < length)
        {
            int number = rnd.Next(1, length + 1);
            if(!myList.Contains(number))
            {
                myList.Add(number);
            }
        }
        return myList;
    }
}

 

抱歉!评论已关闭.