在给定范围内的非重复正随机数

时间:2014-07-09 11:00:47

标签: vb6

使用vb 6.0生成游戏,在一个面上我需要生成1到100之间的非重复随机数。我使用以下代码生成随机数

dim n(10) as integer
for i=0 to 9
n(i)=round(rnd*100) 
next i

代码在for循环中,因此它会随机生成10个Nos,但它包含重复的数字以及' 0',是他们的任何建议,以避免重复数字和' 0&#39 ; 然后我的代码的输出是:

N()= {的 42 下,14,10,22,5,的 42 下,12,的 0 下,59,72} < / p>

数字42在数组中出现两次,0无法避免

提前致谢

3 个答案:

答案 0 :(得分:2)

这是一个简单的技术

Dim n(10) As Integer
Dim choice(100) As Integer
' Create a list of possible numbers
For i = 0 To 100
    choice(i) = i
Next
' Populate the array with unique numbers
For i = 1 To 10
    lastix = 101 - i
    ' Find one that has not been selected
    ix = Round(Rnd * lastix)
    ' Assign it
    n(i) = choice(ix)
    ' Replace with one that has not been used
    choice(ix) = choice(lastix)
Next

您可以使用相同的技术来洗牌。

答案 1 :(得分:1)

要避免0,请乘以99并添加1.要避免重复,请跟踪生成的内容,如果重复,请重试。 (因为你只需要几个数字。如果你需要很多数字,可以随机抽取一系列可能的结果并接受初始成员。)

答案 2 :(得分:-1)

下面的解决方案并不是最快的解决方案,但由于这一点很容易弥补......

它使用隐藏的列表框控件,其中包含所需的值,并且每次都会随机返回

此示例中的值只是索引的平方数

运行项目并单击命令按钮以查看会发生什么。它应该以随机顺序显示带有方形数字的消息框

'1 form with:
'1 listbox control : name=List1
'1 command button  : name=Command1
Option Explicit

Private Sub Command1_Click()
  Dim intIndex As Integer
  'generate a new random sequence every time
  Randomize Timer
  'loop through the list and retreive 1 random value at a time
  With List1
    Do While .ListCount > 0
      intIndex = Int(Rnd * .ListCount)
      MsgBox .List(intIndex)
      'remove the used item from the list
      .RemoveItem intIndex
    Loop
  End With 'List1
End Sub

Private Sub Form_Load()
  Dim intIndex As Integer
  'hide listbox
  List1.Visible = False
  'fill listbox with values (squares)
  List1.Clear
  For intIndex = 1 To 10
    List1.AddItem CStr(intIndex * intIndex)
  Next intIndex
End Sub

顺便说一下,我只是使用10个号码,所以你不必点击100个留言箱:)

相关问题