如何插入另一条指令以避免重复数字,因为所有六个数字应该彼此不同?
以下是我的Visual Basic模块的代码:
Module Loto
Sub Main()
Dim Value1, Value2, Value3, Value4, Value5, Value6 As Integer
Console.WriteLine("Example 3: To generate six numbers from 1 to 40")
Console.WriteLine()
'Initialize the random-number generator.
Randomize()
'Generate a random value between 1 and 40.
'Int((HighestValue - LowestValue + 1) * Rnd) + LowestValue
Value1 = CInt(Int((40 * Rnd()) + 1))
Value2 = CInt(Int((40 * Rnd()) + 1))
Value3 = CInt(Int((40 * Rnd()) + 1))
Value4 = CInt(Int((40 * Rnd()) + 1))
Value5 = CInt(Int((40 * Rnd()) + 1))
Value6 = CInt(Int((40 * Rnd()) + 1))
Do While (Value1 = Value2)
Value2 = CInt(Int((40 * Rnd()) + 1))
Loop
Console.WriteLine("Random number generated is " & Value1)
Console.WriteLine("Random number generated is " & Value2)
Console.WriteLine("Random number generated is " & Value3)
Console.WriteLine("Random number generated is " & Value4)
Console.WriteLine("Random number generated is " & Value5)
Console.WriteLine("Random number generated is " & Value6)
Console.ReadLine()
End Sub
End Module
答案 0 :(得分:2)
我喜欢Plutonix提到的方向,即使用Random
类,但它可以缩短它:
Dim r As New Random
Dim a = Enumerable.Range(1, 40)
Dim b = a.OrderBy(Function() r.Next).Take(6)
答案 1 :(得分:1)
.NET提供了比传统VB更好的随机生成器。基本上,您希望创建一个值数组并交换它们,以便不重复任何数字。
这称为随机播放,因为您实际上并未选择随机数,而是将一组值(如一副牌或一系列数字)放入随机顺序。
Dim rValues(39) As Integer ' random values holder
Dim rand = New Random() ' NET random generator - do this ONCE
Dim temp As integer
随机播放整数数组:
For ndx As Int32 = rValues.Length - 1 To 0 Step-1
Dim r = rand.Next(n + 1) ' next value
temp = rValues(ndx) ' swap values
rValues(ndx) = rValues(r)
rValues(r) = temp
Next
如果用于卡片组,请从rValues(0)
开始选择值,直至结束。要获得6,那么第一个就不会有任何重复。
作为就地洗牌,它非常有效。
答案 2 :(得分:1)
我的$ .02
Private Shared prng As New Random
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim a As List(Of Integer) = (From x In Enumerable.Range(1, 40)
Order By prng.Next Take 6).ToList
For Each n As Integer In a
Debug.WriteLine(n)
Next
End Sub
答案 3 :(得分:0)
创建一个数组1..40,得到一个随机数1..40,用pos(40)处的值交换该位置的值,得到一个随机数1..39并用pos交换该值( 39)...最后你的数字是35:40
答案 4 :(得分:0)
为你的答案创建一个数组并在每一轮之后检查它:
dim resultArr(6) as integer
dim unique as boolean
for i=0 to 5
unique=false
while not unique
resultArr(i)=CInt(Int((40 * Rnd()) + 1))
for j=0 to i-1
unique=(unique OR resultArr(j)<>resultArr(i))
next
wend
next