`

产生随机不重复的数

 
阅读更多
/// <summary>  
/// 从1到33中任意选取不重复的6个随机数  
/// </summary>  
/// <returns></returns>  
public List<int> GenerateNumber1()  
{  
    //用于保存返回的结果  
    List<int> result = new List<int>(6);  
    Random random = new Random();  
    int temp = 0;  
    //如果返回的结果集合中实际的元素个数小于6个  
    while (result.Count < 6)  
    {  
        //在[1,34)区间任意取一个随机整数  
        temp = random.Next(1, 34);  
        if (!result.Contains(temp))  
        {  
            //如果在结果集合中不存在这个数,则添加这个数  
            result.Add(temp);  
        }  
    }  
    //result.Sort();//对返回结果进行排序  
    return result;  



/// <summary>  
/// 从1到33中任意选取不重复的6个随机数  
/// </summary>  
/// <returns></returns>  
public List<int> GenerateNumber2()  
{  
    //用于存放1到33这33个数  
    List<int> container = new List<int>(33);  
    //用于保存返回结果  
    List<int> result = new List<int>(6);  
    Random random = new Random();  
    for (int i = 1; i <= 33; i++)  
    {  
        container.Add(i);  
    }  
    int index = 0;  
    int value = 0;  
    for (int i = 1; i <= 6; i++)  
    {  
        //从[0,container.Count)中取一个随机值,保证这个值不会超过container的元素个数  
        index = random.Next(0, container.Count);//谢谢热心朋友指出这里的错误  
        //以随机生成的值作为索引取container中的值  
        value = container[index];  
        //将随机取得值的放到结果集合中  
        result.Add(value);  
        //从容器集合中删除这个值,这样会导致container.Count发生变化  
        container.RemoveAt(index);  
        //注意这一句与上面一句能达到同样效果,但是没有上面一句快  
        //container.Remove(value);  
    }  
    //result.Sort();排序  
    return result;  


public int[] GenerateNumber3()  
{  
    //用于存放1到33这33个数  
    int[] container = new int[33];  
    //用于保存返回结果  
    int[] result = new int[6];  
    Random random = new Random();  
    for (int i = 1; i <= 33; i++)  
    {  
        container[i - 1] = i;  
    }  
    int index = 0;  
    int value = 0;  
    for (int i = 0; i < 6; i++)  
    {  
        //从[1,container.Count + 1)中取一个随机值,保证这个值不会超过container的元素个数  
        index = random.Next(1, container.Length-1-i);  
        //以随机生成的值作为索引取container中的值  
        value = container[index];  
        //将随机取得值的放到结果集合中  
        result[i]=value;  
        //将刚刚使用到的从容器集合中移到末尾去  
        container[index] = container[container.Length - i-1];  
        //将队列对应的值移到队列中  
        container[container.Length - i-1] = value;  
    }  
    //result.Sort();排序  
    return result;  



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics