正在检查随机数是否已存在VBscript



我写了一段代码,可以生成1-9之间的随机数。

我现在想添加到其中并生成一个随机数,但如果该数以前已经使用过,则生成一个新数。

Sub main()
Dim max,min
max=9
min=1
Randomize
MsgBox(Int((max-min+1)*Rnd+min))

//生成1-9之间的随机数

我曾试图实现一个循环,但我不确定它将如何工作,因为我需要将生成的数字保存在内存中

If Int =  random
Msgbox("Already in use")
End If
If Int = not random Then
Msgbox("Can be used")
End If
End Sub

听起来你只是想跟踪已经选择了哪些随机数。你可以用多种不同的方式处理这个问题(例如,使用数组、哈希表/字典、数字位掩码等(

我下面给出的解决方案类似于数字位掩码,但使用了字符串。从全零开始(例如"0000"(,字符串中的每个可索引位置都填充一(1(,直到字符串变为全一(例如"1111"(。虽然可能过于简单化了——因为它假设你的最小值总是一(1(——但它应该让你开始。

Dim min : min=1
Dim max : max=9
Dim result : result = ""
Dim r, s: s = String(max, "0")
Randomize
Do
r = Int((max-min+1)*Rnd+min)
If "0" = Mid(s, r, 1) Then
WScript.Echo "Can be used: " & r
result = result & ":" & r
s = Left(s, r-1) & "1" & Right(s, max-r)
Else
WScript.Echo "Already in use: " & r
End If
Loop Until String(max, "1") = s
WScript.Echo "Result" & result

样本输出:

Can be used: 4
Can be used: 5
Can be used: 9
Can be used: 3
Already in use: 3
Can be used: 1
Can be used: 8
Can be used: 6
Already in use: 6
Can be used: 7
Already in use: 8
Already in use: 4
Already in use: 3
Already in use: 1
Already in use: 6
Can be used: 2
Result:4:5:9:3:1:8:6:7:2

希望这能有所帮助。

最新更新