取亂數,我想這問題應該是在簡單不過的程式,
但要取出一堆不重複的亂數...有許多效率方面的想法,
有一個是洗牌法,
想法即是先取得一個順序的牌組(陣列),
在隨機取兩個數字後將兩個位子的牌對調,
以下範例是需要進來的牌組多大,就對掉牌組的100倍次數
這CODE不一定完美,但也是一個不錯的取亂數想法。

~Shael

 

 Public Function shuffle(ByVal pNum As Integer, ByVal pPool As Integer) As Integer()
Dim rnd As New Random()
Dim rand1 As Integer
Dim rand2 As Integer
Dim tmp As Integer
'回傳牌
Dim Cards(pNum - 1) As Integer

'取得順序的牌組(包含0)
Dim Decks(pPool) As Integer
For i As Integer = 0 To pPool - 1
Decks(i) = i
Next

'洗牌(牌組多少張就洗張數*100幾次)
For i = 0 To (pPool - 1) * 100
rand1 = rnd.Next(0, Decks.Length - 1)
rand2 = rnd.Next(0, Decks.Length - 1)
tmp = Decks(rand1)
Decks(rand1) = Decks(rand2)
Decks(rand2) = tmp
Next

'取牌
For i = 0 To pNum - 1
Cards(i) = Decks(i)
Next
Return Cards
End Function

 

arrow
arrow
    創作者介紹
    創作者 shael 的頭像
    shael

    Shael

    shael 發表在 痞客邦 留言(0) 人氣()