生成随机整数

时间:2014-07-01 20:42:12

标签: vb.net math random numbers integer

我喜欢生成List(整数),我试图检查没有随机数字出现两次:

Public Shared Function GenerateRandomUniqueNumbers(ByVal Amount As Integer)
As List(Of Integer)
    Dim rnd As New System.Random
    Dim CreatedRandoms As New List(Of Integer)
    For i As Integer = 0 To Amount
        Dim Current As Integer = rnd.Next(1, 999999999)
        If Not CreatedRandoms.Contains(Current) Then
            CreatedRandoms.Add(Current)
        End If
        i += 1
    Next
    Return CreatedRandoms
End Function

但是当我传递10作为数量时它只输出6(该列表只包含6个项目......?有什么想法吗?

3 个答案:

答案 0 :(得分:2)

可能是因为它产生了重复值。

你可以这样做,但显然你无法保证它可能运行多长时间:

Public Shared Function GenerateRandomUniqueNumbers(ByVal Amount As Integer) As List(Of Integer)
    Dim rnd As New System.Random
    Dim CreatedRandoms As New List(Of Integer)
    Do While CreatedRandoms.Count() < Amount
        Dim Current As Integer = rnd.Next(1, 999999999)
        If Not CreatedRandoms.Contains(Current) Then
            CreatedRandoms.Add(Current)
        End If
    Loop
    Return CreatedRandoms
End Function

答案 1 :(得分:1)

如果列表中存在变量,则无法增加计数器:

For i As Integer = 0 To Amount
    Dim Current As Integer = rnd.Next(1, 999999999)
    If Not CreatedRandoms.Contains(Current) Then
        CreatedRandoms.Add(Current)
    End If
    i += 1
    ^^^^^^^
Next

将其更改为:

Public Shared Function GenerateRandomUniqueNumbers(ByVal Amount As Integer)
As List(Of Integer)
    Dim rnd As New System.Random
    Dim CreatedRandoms As New List(Of Integer)
    For i As Integer = 0 To Amount
        Dim Current As Integer = rnd.Next(1, 999999999)
        If Not CreatedRandoms.Contains(Current) Then
            CreatedRandoms.Add(Current)
            i += 1
        End If
    Next
    Return CreatedRandoms
End Function

如果无法生成其他随机数,您还应添加中断条件。这是不太可能的,但更容易想象如果你的金额变大和/或随机数发生器的周期较短。也许是这样的:

Dim repetition As Integer = 0;

   For i As Integer = 0 To Amount

        /* Has max limit of repetitions been reached so far? */
        If repetition > MAX_REPETITIONS Then exit_report_error()

        /* generate new value */
        Dim Current As Integer = rnd.Next(1, 999999999)

        If Not CreatedRandoms.Contains(Current) Then
            CreatedRandoms.Add(Current)
            i += 1
            repetition = 0   // reset counter
        Else
            repetition += 1  // accumulate repetitions
   Next

答案 2 :(得分:0)

没关系,发现错误,不得不删除i + = 1

这是手动递增已经自动递增的计数器。