我想从0-9的范围内生成10个不同的数字.所需的输出可能如下所示,9 0 8 6 5 3 2 4 1 7
Dim arraynum(9) As Integer
Dim crmd As Boolean
Dim rmd as integer
For i = 0 To 9
arraynum(i) = -1
Next i
crmd = True
Randomize Timer
For i = 0 To 9
rmd = Int(Rnd * 10)
For j = 0 To 9
If arraynum(j) = rmd Then
j = 9
If crmd = False Then
i = i - 1
End If
crmd = True
Else
crmd = False
End If
Next j
If crmd = False Then
arraynum(i) = rmd
QuestionILabel.Caption = QuestionILabel.Caption + Str(arraynum(i))
End If
Next i
Run Code Online (Sandbox Code Playgroud)
pax*_*blo 12
选择随机值然后扔掉那些你已经使用过的值是一个坏主意.随着可用数量池越来越少,它会使运行时间变长,因为您丢弃的越来越多.
你想要的是一个随机列表,我将使用以下代码实现(伪代码,因为它的功课):
dim n[10] // gives n[0] through n[9]
for each i in 0..9:
n[i] = i // initialize them to their indexes
nsize = 10 // starting pool size
do 10 times:
i = rnd(nsize) // give a number between 0 and nsize-1
print n[i]
nsize = nsize - 1 // these two lines effectively remove the used number
n[i] = n[nsize]
Run Code Online (Sandbox Code Playgroud)
只需从池中选择一个随机数,然后将其替换为该池中的顶部数字并减小池的大小,即可获得一个随机播放,而无需担心前面的大量交换.如果数量很高,这很重要,因为它不会引入不必要的启动延迟.
例如,检查以下基准检查:
<--------- n[x] ---------->
for x = 0 1 2 3 4 5 6 7 8 9 nsize rnd(nsize) output
--------------------------- ----- ---------- ------
0 1 2 3 4 5 6 7 8 9 10 4 4
0 1 2 3 9 5 6 7 8 9 7 7
0 1 2 3 9 5 6 8 8 2 2
0 1 8 3 9 5 6 7 6 6
0 1 8 3 9 5 6 0 0
5 1 8 3 9 5 2 8
5 1 9 3 4 1 1
5 3 9 3 0 5
9 3 2 1 3
9 1 0 9
Run Code Online (Sandbox Code Playgroud)
您可以随时查看游泳池的减少情况,因为您总是将未使用的游泳池替换为未使用的游泳池,因此您永远不会重复游戏.
而现在你的功课,包括转向到这一点VB的:-)
而且,由于这项作业现在几乎肯定已经过期(大约一年前),我将发布一个VBA解决方案,展示如何做到这一点,以确保完整性.
Option Explicit
Option Base 0
Sub Macro1()
Randomize
Dim list(10) As Integer
Dim i As Integer
Dim size As Integer
Dim pos As Integer
Dim result As String
For i = 0 To 9
list(i) = i
Next
size = 10
result = ":"
For i = 1 To 10
pos = Int(Rnd() * size)
result = result & list(pos) & ":"
size = size - 1
list(pos) = list(size)
Next
MsgBox result
End Sub
Run Code Online (Sandbox Code Playgroud)
这在三个单独的运行中生成:
:5:7:4:2:9:1:0:8:3:6:
:3:9:6:0:7:8:5:4:2:1:
:7:6:3:5:1:8:9:0:4:2:
Run Code Online (Sandbox Code Playgroud)