Question

I wish to generate a random number between 1 and 26 with a seed but then wish to get the same numbers back when I provide the function with the same seed.

The Rnd and Randomize functions aren't suitable for this as they always return a completely random number, regardless of the seed.

Was it helpful?

Solution

Bizarrely, you need to call Rnd(-1) first, then Randomize(n) with n the seed.

Subsequent calls to Rnd() will always give you the same sequence

e.g.

Sub test()

    Call Rnd(-1)
    Call Randomize(0)
    For n = 1 To 10
        Debug.Print Rnd
    Next n

End Sub

OTHER TIPS

Use new instances of System.Random class is one possible solution, and initialize each instance with the same seed.

Sub Main()
    Dim yourSeed = 40 'Or whatever your seed it
    Dim random1 As New System.Random(yourSeed)
    Console.WriteLine(random1.Next(1, 26)) 'Prints 16
    Console.WriteLine(random1.Next(1, 26)) 'Prints 14
    Console.WriteLine(random1.Next(1, 26)) 'Prints 19

    Dim random2 As New System.Random(yourSeed)
    Console.WriteLine(random2.Next(1, 26)) 'Prints 16
    Console.WriteLine(random2.Next(1, 26)) 'Prints 14
    Console.WriteLine(random2.Next(1, 26)) 'Prints 19
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top