关于随机数无重复填充数组问题

前言:

    有一题:产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。

之前一直做不出结果,认为是中间循环太多,陷入无限等待呢?!后来发现是Random函数理解有误。

 

解析:

     代码演示:

    // Description: 演示无重复填充数组随机数问题

    
// CopyRight: http://www.cnblogs.com/yangmingming

    
// Notes: 选取1-100数字填充,具有int[100]

    
class Program
    {
         
static int[] arrInt = new int[100];
        
//功能函数
         public static bool ExistAnyNumber(int ran, int count)
         {
             
for (int i = 0; i < count; i++)
             {
                 
if (ran == arrInt[i])
                     
return true;
             }
             
return false;

 
         }
         
static void Main(string[] args)
        {
           
            Random a 
= new Random();
            
            
for (int i = 0; i < 100; i++)
            {
                
//初始获取1-100随机数的方法
                int ran = a.Next(1100);

                
//修正后的方法
                int ran = a.Next(1100);
                
while (ExistAnyNumber(ran, i))
                {
                    
// ran = a.Next(1, 100);
                    ran = a.Next(1101);
                }
                arrInt[i] 
= ran;

            }
            
for (int i = 0; i < 100; i++)
                Console.WriteLine(
"{0} ",arrInt [i]);
           
        }
    }


 是啊,原来问题出在了如此小的细节上,这才发现“多总结,多思考,多注意细节!”是多么的重要啊。

 

posted @ 2010-04-01 15:09  Youngman  阅读(725)  评论(0编辑  收藏  举报