我試圖做一個交易或不交易的遊戲,但是我現在的問題是隨機爲案例分配設置值。我沒有隨機生成一個數字並檢查它是否已經存在,所以我現在試圖簡單地洗牌數組。問題是,出於某種原因,值重複。 代碼:VB:Random Shuffler Duplicating Values
Dim nCaseValues(26) As Integer 'The different possible values for a case
Dim nCaseNumbers(26) As Integer 'The different case numbers
Dim nShadowNumber As Integer 'This holds the first number in the shuffle
Dim nShuffleNumber1 As Integer 'The first random position
Dim nShuffleNumber2 As Integer 'The second random position
'Clear the list if it already has content
listArray1.Items.Clear()
listArray2.Items.Clear()
listArray3.Items.Clear()
'Declare array for case values
nCaseValues(0) = 1500
nCaseValues(1) = 1
nCaseValues(2) = 2
nCaseValues(3) = 5
nCaseValues(4) = 10
nCaseValues(5) = 20
nCaseValues(6) = 50
nCaseValues(7) = 100
nCaseValues(8) = 150
nCaseValues(9) = 200
nCaseValues(10) = 250
nCaseValues(11) = 500
nCaseValues(12) = 750
nCaseValues(13) = 1000
nCaseValues(14) = 2000
nCaseValues(15) = 3000
nCaseValues(16) = 4000
nCaseValues(17) = 5000
nCaseValues(18) = 10000
nCaseValues(19) = 15000
nCaseValues(20) = 20000
nCaseValues(21) = 30000
nCaseValues(22) = 50000
nCaseValues(23) = 75000
nCaseValues(24) = 100000
nCaseValues(25) = 200000
'Declare array for case numbers
For genCaseNumArray = 0 To 25
nCaseNumbers(genCaseNumArray) = 0
listArray1.Items.Add(genCaseNumArray)
Next
'The shuffle
For J = 0 To 25 'This assigns case values to case numbers (It's probably moot, as I can just use the nCaseValues position, but it's here for now)
nCaseNumbers(J) = nCaseValues(J)
Next
For K = 0 To 25 'Lists the items below, this could possibly be an error
For I = 0 To 50 'Shuffles the list 50 times
nShuffleNumber1 = (Int(Rnd() * 26)) 'Gets a random number and assigns it
nShuffleNumber2 = (Int(Rnd() * 26))'Gets a random number and assigns it
nShadowNumber = nCaseNumbers(nShuffleNumber1) 'This holds the first value during the shuffle
nCaseNumbers(nShuffleNumber1) = nCaseNumbers(nShuffleNumber2)'First value now equals second value...
nCaseNumbers(nShuffleNumber2) = nShadowNumber 'And now second value holds first value.
Next 'Lists items in lists objects on the form
listArray1.Items.Add(K)
listArray2.Items.Add(nCaseValues(K))
listArray3.Items.Add(nCaseNumbers(K))
Next
我需要每個值是唯一的。我很確定這是我的代碼中的邏輯錯誤。任何關於數字爲什麼重複的幫助都會很好。
這裏有一對夫婦的輸出:
第一清單的案件編號,二是爲了可能的值,第三個是最終的結局 - 個案價值。正如你所看到的,一些是重複的,第一個列表重複兩次..編輯:我發現它爲什麼重複兩次 - 我很愚蠢,留下另一個循環,這也是添加到列表中。我已經解決了我的問題,請參閱下面的答案。
這只是不正確的方式來獲得隨機洗牌。你用一副52張牌做的方式是首先得到0到51之間的一個隨機數。取出相應的牌。接下來得到0到50之間的一個隨機數字,拿出卡片。接下來在0和49之間。等等,重複,直到甲板空了。 Google「vb.net fisher yates shuffle」,很多熱門歌曲。 –