2017-02-21 368 views
-3

我见过很多教程,但它似乎没有为我工作。我需要生成随机数字而不重复。生成随机数字而不重复

这是我的代码:

Dim intNumber As Integer 
    Dim arrNumber(0 To 0) As Integer 
    Dim i, x, y As Integer 
    'Make sure the Label is clear 
    Label1.Text = "" 



    For x = 0 To 0 
Start: 
     intNumber = Int((25 * Rnd()) + 1) ' Random number 1 to 25 
     For y = 0 To 0 
      ' Check arrNumber (y) 
      'If intnumber has already been selected, 
      'Then go and select another one. 
      If intNumber = arrNumber(y) Then 
       GoTo Start 
      End If 
     Next y 

     'Place the next non-repeated number in the arrNumber(x). 

     arrNumber(x) = intNumber 


    Next x 

    '---------------------------------------------------- 
    For i = 0 To 0 

     Label1.Text = Label1.Text & (arrNumber(i)) 
     broj1.random.Text = Label1.Text 
    Next 

End Sub 
+0

在没有看到代码,我只能猜测,你是初始化随机数发电机不止一次,这将导致生成相同的数字。 –

+0

对不起,我编辑后我插入我以前使用的代码 – AceDuk

+0

请[编辑]你的问题澄清。你是以随机顺序查找数字1到25吗?请理解它有时随机重复的内在随机性。查看“生日悖论”。 –

回答

1

你的问题,尤其是在VB,难以解决。你正在寻找一个随机成交,而不是随机滚。也就是说,您正在寻找一个赌场经销商仿效一张一张洗牌25张牌的牌,而不是一个经销商旋转25槽轮盘。

有一件事情让它很难处理。改组?按同样的顺序处理?

这是一个关于这个话题的体面的文章。 http://www.4guysfromrolla.com/articles/070208-1.aspx

这里有一些C#代码来处理。

private static List<int> _deck = null; 
    private static readonly Random NumberGenerator = new Random(); 
    public static int Deal() 
    { 
     if (_deck == null || _deck.Count == 0) 
     { 
      /* new deck */ 
      _deck = new List<int>(); 
      for (var i = 0; i <= 24; i++) _deck.Add(i); 
     } 

     /* get a random card from the remaining deck */ 
     var next = NumberGenerator.Next(0, _deck.Count); 
     /* retrieve the card's number */ 
     var q = _deck[next]; 
     /* and remove the card from the deck */ 
     _deck.RemoveAt(next); 
     /* return in range 1-25 */ 
     return q + 1; 
    } 
+0

谢谢...... :) – AceDuk

1

有时你需要学习如何建立时钟,有时候你只需要知道时间:

Const HowMany As Integer = 25  ' how many numbers do you want? 

    Dim Used As New List(Of Integer) 
    Used.Add(0)      ' position zero has 0, all other positions have a generated counting number 

    For i = 1 To HowMany 
     Dim OK As Boolean = False  ' OK becomes true when a unique number has been generated 
     Do 
      Dim num As Integer = Int((HowMany * Rnd()) + 1) 
      If Used.Contains(num) Then 
       OK = False   ' we'll try again shortly 
      Else 
       OK = True   ' this round is complete -- found a unique number 
       Used.Add(num)  ' add the generated number to the list 
      End If 
     Loop Until OK  ' in other words, loop until we've found a unique number 
    Next 

    For i = 1 To HowMany 
     MsgBox(Used(i)) ' or just use the list in however you need 
    Next 
+0

建议:当你有一个像这个例子一样的固定序列时,使用Dim Used(25)作为布尔值并测试/设置索引值会更高效。尽管在这种情况下这是无效的,因为他想在事实之后转储它们。 –

+1

当然。对于少数值,效率无关紧要,对于简单演示,我使用了一个列表,而不是布尔值数组加上列表/结果数组。但是,当所需值的数量变大时,对'Used(986)= True'的测试将比'Used.Contains'代码检查这个特定值的数百个元素要快得多。 – ConfusionTowers

+0

因此,如果工作的代码可以用于更多标签?标签数组? – AceDuk