vbscript - 检查随机数是否已经存在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),直到字符串变为全 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
希望这可以帮助。
推荐阅读
- django - 如何在 django 中检索通过表单(不是通过基于模型的模型表单)输入的数据
- java - 如何运行 jar。云 ubuntu 服务器上的文件?
- javascript - JavaScript 异步帮助 - 用于计算方向的 Google Maps JavaScript API
- bluetooth - BLE 外设无法正确显示
- arrays - GLSL 中可调整大小的数组
- python-3.x - 熊猫数据框上的多个日期操作
- python - 如何在 python 脚本上使用命令 azure cli 导出数据库
- for-loop - 当我按下 button2 时,我希望我的代码显示 4 form2 但它不会为什么呢?
- c++ - 分段错误线程
- javascript - Node.js readline 行为怪异