2018年3月19日 星期一

[VB.NET] 取範圍內亂數(不重複)

最近因工作需求寫了個範圍內不重複取亂數,怕遺忘先筆記起來,寫法如下:


'宣告陣列長度為5
Dim RandomList(5) As Integer
'宣告變數
Dim i, j As Integer
'宣告布林值
Dim ynum, zero As Boolean
'宣告暫存數
Dim rndnum, temp As Integer
'宣告亂數函數
Dim RandomFactory As New Random()

Do
        '亂數範圍值從0到5
        rndnum = RandomFactory.Next(0, 5)
        ynum = False

        '找到重覆亂數
        For i = 0 To UBound(RandomList)
               '判斷陣列中的0與亂數0(當前只判斷一次)
                If (zero = True And rndnum = 0) = True Then
                        zero = False : Exit For
                End If
                '當亂數重複時候即重新始
                If rndnum = RandomList(i) Then
                        ynum = True : Exit For
                End If
        Next

        '不重覆亂數放置到陣列
        If ynum = False Then
                RandomList(j) = rndnum
                j = j + 1
                If j > UBound(RandomList) Then Exit Do
        End If
Loop

'陣列取亂數值
For Each temp In RandomList
        '這裡寫自己需要的程式碼
        '以下當亂數等於0時候要處理的事件
        If rndnum = 0 Then
        '這裡寫自己需要的程式碼
        End If
Next