2018年6月20日 星期三

C# x 1到100陣列 x 隨機不重複


昨天去xx看到不錯的考題,當下沒有解出來,寫了不隨機不重複的Code,後來回家想想才發現原來這麼簡單...



using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rd = new Random();
            string strNum="";
            int[] ai = new int[100];
            int rNum;
            for (int i = 1; i <= 100; i++)
            {
                rNum = rd.Next(1, 101);//取亂數
                if (Array.IndexOf(ai, rNum) == -1)//用Array.IndexOf判斷有沒有重複,沒有重複的話回傳值就是-1
                {
                    ai[i - 1] = rNum;
                }
                else//用Array.IndexOf判斷有沒有重複,有重複就會到這裡
                {
                    while (Array.IndexOf(ai, rNum) != -1)//如果不等於 -1 那就在重新跑一次亂數取值,直到等於-1
                    {
                        rNum = rd.Next(1, 101);
                    }
                    ai[i - 1] = rNum;//Array.IndexOf = -1 就會跳出while迴圈 走到這裡
                }
            }

            foreach (int strnum in ai) //將陣列的值取出
            {
                strNum += strnum.ToString()+" , ";
            }
            Console.WriteLine(strNum);
            Console.ReadLine();
        }
    }
}

沒有留言:

張貼留言