首页 > 解决方案 > 检查随机数是否已经存在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

标签: vbscript

解决方案


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

我在下面提出的解决方案类似于数字位掩码,但使用了字符串。从全零开始(例如,“0000”),字符串中的每个可索引位置都会填充一 (1),直到字符串变为全 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

希望这可以帮助。


推荐阅读