none
Random Number Generation RRS feed

  • Question

  • I'm writing a jukebox in Visual Studio vb.net. I'm attempting to utilise random number generators to swap the image of the record label being played (which works fine)

        Dim r As New System.Random(CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, Integer))
    
        Public Function GetRandomNumber(Optional ByVal Low As Integer = 1, Optional ByVal High As Integer = 100) As Integer
            ' Returns a random number, between the optional Low and High parameters
            Return r.Next(Low, High + 1)
    
        End Function
    
            gRecordLabelImage = gDefaultLabelImage(GetRandomNumber(0, gDefaultLabelImageCount - 1))
    
    

    However, when trying to utilise this code to get the next 5 records to be played (when implementing random play), the code calls work first time through but give me the same 5 random numbers on the next call.

    For LoopCounter = 1 To 5
    Counter = GetRandomNumber(1,TracksDataSet.Count - 1)
    gTrackFileName = TracksDataSet(Counter).PlayListTrackFileName
    Next

    I've tried RNGCryptoService Provider

        Dim Provider As New RNGCryptoServiceProvider()
        Public Function GenerateRandom(ByRef MaxValue As Integer) As Integer
            Dim result As Integer
            Using Provider
                Dim data As Byte() = New Byte(3) {}
                Provider.GetBytes(data)
                result = (BitConverter.ToUInt32(data, 0) Mod MaxValue) + 1
            End Using
            Return Result
        End Function
    For LoopCounter = 1 to 5
    Counter = GenerateRandom(TracksDataSet.Count)
    gTrackFileName = TracksDataSet(Counter).PlayListTrackFileName
    Next

    But this does exactly the same. Please note though that the 5 repeated random numbers are different every time code is started, they just repeat while code is running.

    I've worn myself out in Google and web forums - they all say the same - the code should work, so what is my problem. Any Help gratefully accepted

    thanks - Graeme Baillie

    Wednesday, February 12, 2020 5:02 PM

Answers


  • My code asks for 5 random numbers in a loop which it gets, all different - the code uses these 5 numbers to play 5 tracks from my music library. When I detect that the last record is playing the code asks for another 5 random numbers - however this time it is the same 5 numbers I got before.

    My question is why in this circumstance is the random seed being reset for Rnd or Random

    I don't think you have given enough context for us to be able to analyze your
    problem. The symptoms you describe are exactly what one sees when the
    RNG is created/seeded with the same seed value for successive calls.

    This can happen for example when the RNG object is created and a set of numbers 
    generated in a tight, rapid loop. The value used from a timer may not be unique
    on each iteration so the RNG gets seeded multiple times with the same value.

    Or when the RNG is recreated using a seed value that was calculated and stored
    earlier, so a new RNG object is created each time using the same seed value.
    Since these are pseudo-random number generators the algorithm will always
    generate the same set of values every time the same seed value is used.

    You *should* see three different sets of five numbers when you run the following code.

    Module Module1
        Dim r As New System.Random(CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, Integer))
        Dim Counter As Integer
    
        Sub Main()
            For Outer_LoopCounter = 1 To 3
                For LoopCounter = 1 To 5
                    Counter = GetRandomNumber()
                    Console.WriteLine(Counter)
                Next
                Console.WriteLine()
            Next
        End Sub
    
        Public Function GetRandomNumber(Optional ByVal Low As Integer = 1, Optional ByVal High As Integer = 100) As Integer
            ' Returns a random number, between the optional Low and High parameters
            Return r.Next(Low, High + 1)
        End Function
    
    End Module
    

    - Wayne

    • Marked as answer by GraemeFBaillie Thursday, February 13, 2020 11:21 AM
    Thursday, February 13, 2020 12:57 AM
  • Hi GraemeFBaillie,

    Thank you for posting here.

    To avoid getting duplicate random values, you can try this:

    Dim rand As Random = New Random(Guid.NewGuid().GetHashCode())

    Besides, here's a reference about generating random, unique values, and you can convert the c# code to VB.

    Generating random, unique values C#

    Hope suggestions in the references could be helpful.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by GraemeFBaillie Thursday, February 13, 2020 11:21 AM
    Thursday, February 13, 2020 2:54 AM
    Moderator
  • Try the next definition of r too:

       Shared r As New System.Random()

     

    • Marked as answer by GraemeFBaillie Thursday, February 13, 2020 11:21 AM
    Thursday, February 13, 2020 7:40 AM

All replies

  • 1. Create an array of your values.

    2. x = array.length

    3. Choose a random number between 0 and x - 1.

    4. Do what you need and then remove the item from the array.

    5. Loop to 2.


    George Frias - AWWshop @ Wikidot, Wiki1978

    Wednesday, February 12, 2020 5:43 PM
  • Choosing a random number is not the issue, nor is choosing a distinct random number, what I don't want is to get back the same 5 'random' numbers repeated every time I call the functions.

    Removing an item every time a random number was generated would mean that eventually every track would be played (not really what I'm after - truly random allows for duplicate choices to be made)

    Thanks anyway

    Wednesday, February 12, 2020 5:56 PM
  • I can tell you that I have never seen that with the following:

    Dim TheInstance As Integer
    Dim RandMax As Integer = Instances(CharType)
    Randomize()
    TheInstance = Int((RandMax * Rnd()) + 1)


    George Frias - AWWshop @ Wikidot, Wiki1978

    Wednesday, February 12, 2020 6:47 PM
  • Rnd was deprecated a long time ago and replaced with Random, but as I have said generating a single random number is not an issue - I can do that using Rnd, Random or RNGCryptoServiceProvider.

    My code asks for 5 random numbers in a loop which it gets, all different - the code uses these 5 numbers to play 5 tracks from my music library. When I detect that the last record is playing the code asks for another 5 random numbers - however this time it is the same 5 numbers I got before.

    My question is why in this circumstance is the random seed being reset for Rnd or Random, it shouldn't ever happen for the CryptoService - wouldn't be much use if I was using this to generate two separate 16 character passwords and finding out both were the same.

    Wednesday, February 12, 2020 7:24 PM
  • Have you attempted a Thread.Sleep between calls?

    George Frias - AWWshop @ Wikidot, Wiki1978

    Wednesday, February 12, 2020 7:25 PM
  • That's wrong. There must be a refresh in that tech.

    George Frias - AWWshop @ Wikidot, Wiki1978

    Wednesday, February 12, 2020 7:28 PM
  • This is not in a lambda expression?

    George Frias - AWWshop @ Wikidot, Wiki1978

    Wednesday, February 12, 2020 7:36 PM

  • My code asks for 5 random numbers in a loop which it gets, all different - the code uses these 5 numbers to play 5 tracks from my music library. When I detect that the last record is playing the code asks for another 5 random numbers - however this time it is the same 5 numbers I got before.

    My question is why in this circumstance is the random seed being reset for Rnd or Random

    I don't think you have given enough context for us to be able to analyze your
    problem. The symptoms you describe are exactly what one sees when the
    RNG is created/seeded with the same seed value for successive calls.

    This can happen for example when the RNG object is created and a set of numbers 
    generated in a tight, rapid loop. The value used from a timer may not be unique
    on each iteration so the RNG gets seeded multiple times with the same value.

    Or when the RNG is recreated using a seed value that was calculated and stored
    earlier, so a new RNG object is created each time using the same seed value.
    Since these are pseudo-random number generators the algorithm will always
    generate the same set of values every time the same seed value is used.

    You *should* see three different sets of five numbers when you run the following code.

    Module Module1
        Dim r As New System.Random(CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, Integer))
        Dim Counter As Integer
    
        Sub Main()
            For Outer_LoopCounter = 1 To 3
                For LoopCounter = 1 To 5
                    Counter = GetRandomNumber()
                    Console.WriteLine(Counter)
                Next
                Console.WriteLine()
            Next
        End Sub
    
        Public Function GetRandomNumber(Optional ByVal Low As Integer = 1, Optional ByVal High As Integer = 100) As Integer
            ' Returns a random number, between the optional Low and High parameters
            Return r.Next(Low, High + 1)
        End Function
    
    End Module
    

    - Wayne

    • Marked as answer by GraemeFBaillie Thursday, February 13, 2020 11:21 AM
    Thursday, February 13, 2020 12:57 AM
  • Hi GraemeFBaillie,

    Thank you for posting here.

    To avoid getting duplicate random values, you can try this:

    Dim rand As Random = New Random(Guid.NewGuid().GetHashCode())

    Besides, here's a reference about generating random, unique values, and you can convert the c# code to VB.

    Generating random, unique values C#

    Hope suggestions in the references could be helpful.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by GraemeFBaillie Thursday, February 13, 2020 11:21 AM
    Thursday, February 13, 2020 2:54 AM
    Moderator
  • Try the next definition of r too:

       Shared r As New System.Random()

     

    • Marked as answer by GraemeFBaillie Thursday, February 13, 2020 11:21 AM
    Thursday, February 13, 2020 7:40 AM
  • Thanks for all your suggestions - you will be pleased to know that they all work and produce random numbers for me, as does the methods I used originally. So while I was editing code and debugging furiously - hands up - rookie mistake (and I've been coding for 50 years) - I noticed that I was adding the new random numbers to the end of my array and then trimming the array (wrong end) and resetting the pointer to the beginning of the array, so when I looked at the array it contained not the same numbers but the original random numbers. This is what happens when you are brought up in an environment where every bit counts.

    Sorry to have wasted your time, but as they say - a problem shared.

    Thursday, February 13, 2020 11:19 AM