随机数,不重复

时间:2015-10-31 15:44:08

标签: .net vb.net loops

我一直试图在X和Y之间生成一个没有重复的随机数。所有输出都是0。

以下代码中的错误是什么?使用Loop While,它有效,但我想知道Loop Until代码的问题是什么。

Sub Main()
    Dim X, Y, temp, difference, rNumbers(19) As Integer
    Dim Exist As Boolean = False
    Dim rndm As New System.Random
    Console.WriteLine("Enter the value of X") : X = Console.ReadLine()
    Console.WriteLine("Enter the value of Y") : Y = Console.ReadLine()
    If Y < X Then
        temp = X
        X = Y
        Y = temp
    End If
    difference = Y - X
    If difference < 20 Then
        Console.WriteLine("Error, try again! The difference between X and Y must be greater than 20")
        Main()
    Else
        For Count = 0 To 19
            Do
                temp = rndm.Next(X, Y)
                Exist = False
                For Count_2 As Integer = 0 To Count
                    If temp = rNumbers(Count_2) Then
                        Exist = True
                    End If
                Next
            Loop Until Exist = False
            Console.WriteLine(rNumbers(Count))
        Next
    End If
End Sub

2 个答案:

答案 0 :(得分:0)

虽然我是C#开发人员,但我必须将您的代码转换为C#才能理解完整的逻辑,但我确信这些代码没有理由按预期工作,让我列出一些问题:

  1. int[] rNumbers中填充的值在哪里,我没有看到它在初始化后被填充,因此它将始终包含零并且您正在打印来自相同数组的值,这些值是总是0,因此不能指望任何其他结果

  2. 用户输入X, Y的值,他们需要有一个20的差距,现在在do-while循环中,值temp这是在两者之间生成的随机数X, Y中的值会比较int[] rNumbers,然后只会进一步while loop,但由于比较只与rNumbers数组中的值0进行比较,因此它会除了第一个do-while

  3. 之外,大部分都没有执行do循环
  4. 现在随机数,System.Random是一个伪随机数类,永远不会生成一个真正的随机数,请查看Jon Skeet的以下内容:

  5. True Random Number Generator

    使用System.Cryptography生成真正的随机数

    因此,您需要进行这些重要更改,以期望相关结果

答案 1 :(得分:0)

该算法现在有效。

Sub Main()
    Dim X, Y, temp, difference, rNumbers(19), tempo As Integer
    Dim Exist As Boolean
    Dim rndm As New System.Random
    Console.WriteLine("Enter the value of X") : X = Console.ReadLine()
    Console.WriteLine("Enter the value of Y") : Y = Console.ReadLine()
    If Y < X Then
        temp = X
        X = Y
        Y = temp
    End If
    difference = Y - X
    If difference < 20 Then
        Console.WriteLine("Error, try again! The difference between X and Y must be greater than 20")
        Main()
    Else
        For Count = 0 To 19
            Do
                Exist = False
                tempo = rndm.Next(X, Y)
                For Count_2 As Integer = 0 To Count
                    If rNumbers(Count_2) = tempo Then
                        Exist = True
                    End If
                Next
            Loop Until Exist = False
            rNumbers(Count) = tempo
            Console.WriteLine(rNumbers(Count))
        Next
    End If
End Sub