我目前正在尝试生成随机数,直到出现用户定义的相同数量的数字。数字范围从1到10.
当我想要连续8个相同的数字时需要3到5秒。它经历了大约500万个随机数。当我想要连续9次时,我已经离开它超过45分钟而没有任何运气。
我认为它只花费大约10倍于8的时间,因为1/10到9的幂只比8的幂大十倍。
我的代码是问题还是搞砸了数学?
我的代码:
Sub Main()
Console.WriteLine("how many identical numbers in a row do you want")
Dim many As Integer = Console.ReadLine
Dim storage(many - 1) As Integer
Dim complete As Boolean = False
Dim part As Integer = 0
Dim count As Integer = 0
Randomize()
While complete = False
count += 1
storage(part) = Int(Rnd() * 10) + 1
' Console.WriteLine(storage(part))
part += 1
If part = many Then
part = 0
End If
If storage.Min = storage.Max Then
complete = True
End If
End While
Console.WriteLine("===========")
Console.WriteLine(count.ToString("N"))
Console.WriteLine("===========")
For i = 0 To many - 1
Console.WriteLine(storage(i))
Next
Console.ReadLine()
End Sub
答案 0 :(得分:0)
可能存在多种可能性:可能是VB Rnd函数被编写为无法正常工作,或者有时可能需要很长时间。您必须进行多次试验并将其平均,以确定您的预期比率1:10是否按预期工作。
顺便说一句,您不需要保留最后十个数字。您可以只计算下一个随机数等于前一个数字的次数。另外我建议尝试使用不同的RNG(随机数生成器),例如.NET one:
Module Module1
Dim rand As New Random()
Sub Main()
Console.Write("How many identical numbers in a row do you want: ")
Dim howMany As Integer = CInt(Console.ReadLine)
Dim count As Long = 0
Dim previous = -1
Dim soFar = 0
Dim n = 0
While soFar < howMany
count += 1
n = rand.Next(1, 11)
'Console.Write(n.ToString() & " ")
If n = previous Then
soFar += 1
Else
'If previous >= 0 Then
' Console.WriteLine(" X")
' Console.Write(n.ToString() & " ")
'End If
previous = n
soFar = 1
End If
End While
Console.WriteLine()
Console.WriteLine("Tries taken: " & count.ToString())
Console.ReadLine()
End Sub
End Module