Re: [VB6 ] 關於取亂數不重複

看板Visual_Basic作者 (矇面加菲獅)時間16年前 (2008/06/26 22:32), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)
剛才依照幾位板友的建議,試著用了我沒用過的寫法來寫49選6的亂數值 先把49個數字放在一個暫存的陣列中,再抽出6個數字 (以前我都只會用迴圈去找有沒有重覆,效能很差,還有可能會無窮迴圈) Public Sub Main() Randomize Timer '設定最小值及最大值 Const min As Integer = 1, max As Integer = 49 '設定要取得亂數的數量 Const count As Integer = 6 Dim number() As Integer number = GetRndNumber(min, max, count) Dim i As Integer For i = 0 To count - 1 Debug.Print number(i) & " "; Next Debug.Print End Sub '取得亂數 Public Function GetRndNumber(ByVal min As Integer, ByVal max As Integer, ByVal count As Integer) As Integer() '計算陣列上限 Dim u As Integer u = max - min ReDim buffer(u) As Integer, result(count - 1) As Integer Dim i As Integer, n As Integer '將 min 至 max 範圍的數字依序填入 buffer 陣列中 n = min For i = 0 To u buffer(i) = n If i < u Then n = n + 1 Next For i = 0 To count - 1 n = CInt(Rnd * u) result(i) = buffer(n) Swap buffer(n), buffer(u) u = u - 1 Next '回傳結果 GetRndNumber = result End Function '變數交換 Public Sub Swap(ByRef v1 As Variant, ByRef v2 As Variant) Dim tmp As Variant tmp = v2 v2 = v1 v1 = tmp End Sub -- ▃▅▇▆▄ ▆▂▃ ` 逝去感如何能留住,半點遺留殊不易,██▅▇▄▃ ▇▃▂" . █████████▃i ▁▄▇ 更多悽悽慘慘的遭遇………██▆▃ █▅▆▃ˍ▄* ▂█▄▇▅▂. 我不知道,王~八~蛋~~! ▂▆███ █▄▃ 。fumizuki。Check。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.194.99.129
文章代碼(AID): #18OwXYvl (Visual_Basic)
文章代碼(AID): #18OwXYvl (Visual_Basic)