2013-10-29 133 views
0

我應該添加到隨機數字生成器編碼,所以數字不會連續多次重複自己?Vb.net隨機數字生成器重複相同的數字

我的隨機數生成器看起來是這樣的:

Dim rn As New Random 
TextBox1.Text = rn.Next(1, 4) 
If TextBox1.Text = 1 Then 
    Form4.Show() 
    Form4.Timer1.Start() 
End If 

If TextBox1.Text = 2 Then 
    Form7.Show() 
    Form7.Timer1.Start() 
End If 

If TextBox1.Text = 3 Then 
    Form8.Show() 
    Form8.Timer1.Start() 
End If 
+0

你的意思是你不想要sometthing像'1 2 2/3 1 1/2 3 3'和喜歡的東西'1 3 2/2 1 3/3 1 2'而不是? –

+0

是的,現在它的1 2 2/3 1 1/2 3 3 ...我想要1 3 2/2 1 3/3 1 2 ... – user2932903

+0

隨機數字在這麼小的範圍內重複出現。你可以將最後一個數字存儲爲一個var,並且不斷獲得新的randoms,直到它不符合前一個。 – Plutonix

回答

0

要獲得1至N(含),你可以使用下面的一個隨機整數值。

CInt(Math.Ceiling(Rnd() * n)) 
+0

0到N之間 – NoChance

+0

不適合我... – user2932903

1

鑑於N(目前N = 3,但也可能是別的東西,像你說的),試圖建立的1隨機排列,...,N,然後在命令打開文本框這是生成的。請注意,這意味着您一次生成N個數字並全部使用它們,然後再生成N個數字。搜索「隨機排列」來查找算法。

+0

這是要走的路。爲了簡單起見,您可以輕鬆地交換兩個隨機元素n/2次。 – user1120897

+1

這也叫做「Fisher-Yates」或「Knuth」洗牌。以我的答案爲例。 –

1

移動你的隨機實例,「RN」,出類(表)的水平所以它只被用於表一旦創建,並且同一個實例被反覆使用:

Public Class Form1 

    Private rn As New Random 

    Private Sub SomeMethod() 
     TextBox1.Text = rn.Next(1, 4) 
     If TextBox1.Text = 1 Then 
      Form4.Show() 
      Form4.Timer1.Start() 
     End If 

     If TextBox1.Text = 2 Then 
      Form7.Show() 
      Form7.Timer1.Start() 
     End If 

     If TextBox1.Text = 3 Then 
      Form8.Show() 
      Form8.Timer1.Start() 
     End If 
    End Sub 

End Class 
+0

他不想重複任何號碼 –

+0

修正了它!問題是我有兩個Dim作爲新隨機,現在它工作正常。感謝您的幫助 – user2932903

0

如果你想每個數字只能使用一次,你需要做的是這樣的:

Const FirstNumber As Integer = 1 
Const LastNumber As Integer = 5 

' Fill the list with numbers 
Dim numberList as New List(Of Integer) 
For i As Integer = FirstNumber To LastNumber Step 1 
    numberList.Add(i) 
Next i 

Dim rand as New Random() 
While numberList.Count > 0 
    ' draw a random number from the list 
    Dim randomIndex As Integer = rand.Next(0, numberList.Count - 1) 
    Dim randomNumber As Integer = numberList(randomIndex) 

    ' Do stuff with the number here   
    TextBox1.Text = randomNumber 

    ' remove the number from the list so it can't be used again 
    numberList.RemoveAt(randomIndex) 
End While 
+0

從OP中可以看出,這是否就像是一副撲克牌或擲骰子。 – dbasnett