문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top