產生不重複的隨機數演算法

來源:互聯網
上載者:User

本文轉載http://blog.csdn.net/zhoufoxcn/article/details/5825093#comments

有時我們需要從指定的數值範圍內隨機產生一個數,利用這個偽隨機數去實現自己想要實現的東西。在園子裡看了不少好文章和代碼,發現zhoufoxcn實現這個演算法的思路很好,尤其是第三個方法,

效率較好,便把這一skill記載了下來,雖然我們可以用諸如Random rand = new Random(Guid.NewGuid().GetHashCode()); int value = rand.next(intMin, intMax)代碼實現,但程式員的最大
樂趣在於自己動腦,用不同的思路寫出不同的演算法。
  代碼如下:
View Code View Code 

static List<int> GenerateNumber1()
        {
            List<int> result =new List<int>(100);
            Random random =new Random();
            int temp =0;
            while (result.Count <100)
            {
                temp = random.Next(1, 34);
                if (!result.Contains(temp))
                {
                    result.Add(temp);
                }
            }
            return result;

        }

        static List<int> GenerateNumber2()
        {
            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++)
            {
                index = random.Next(0, container.Count);
                value = container[index];
                result.Add(value);
                container.RemoveAt(index);
            }

            return result;
        }

        staticint[] GenerateNumber3()
        {
            // 用於存放1到33這33個數
int[] container =newint[33];
            //用於儲存返回結果 
int[] result =newint[6];
            Random random =new Random();
            for (int i =0; i <33; i++)
            {
                container[i] = i +1;
            }
            int index =0;
            int value =0;
            for (int i =0; i <6; i++)
            {
                //從[1,container.Count + 1)中取一個隨機值,保證這個值不會超過container的元素個數   
                index = random.Next(0, container.Length - i);
                //以隨機產生的值作為索引取container中的值   
                value = container[index];
                //將隨機取得值的放到結果集合中   
                result[i] = value;
                //將剛剛使用到的從容器集合中移到末尾去   
                container[index] = container[container.Length - i -1];
                //將隊列對應的值移到隊列中   
                container[container.Length - i -1] = value;  

            }
            return result;
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.