oddoneout
oddoneout

Reputation: 23

Generating an array of random strings

I'm trying to build a static array of randomly generated strings of a specific length. I've based what I have so far from here, but each index in the array has the same string, instead of a different strings. What am I doing wrong?

Dim Target As String
 Target = InputBox("Input target string")

  Dim StringArray(10) As String
        For i = 1 To 10
            StringArray(i) = GenerateString(Len(Target))
            Debug.Print(StringArray(i))
        Next

  Function GenerateString(size As Integer) As String
        Dim LegalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        Dim Rnd As New Random()
        Dim Builder As New System.Text.StringBuilder()
        Dim Ch As Char

        For i As Integer = 0 To size - 1
            Ch = LegalCharacters(Rnd.Next(0, LegalCharacters.Length))
            Builder.Append(Ch)
        Next

        Return Builder.ToString()
    End Function

Upvotes: 2

Views: 296

Answers (1)

GeorgDangl
GeorgDangl

Reputation: 2192

This: Dim Rnd As New Random() is where the error happens.

When you instantiate a new Random(), it takes the current time as seed. Since you instantiate it again in every iteration AND all the iteration steps happen at the "same" time (in very fast succession), each Random() generates the same output.

You have to instantiate it once before the iterator and pass it in the function as argument or you could also make it a static property of the class.

TL;DR: You will have to re-use the same Random() instead of creating a new one for each iteration.

This should be the correct code:

Dim Target As String
Target = InputBox("Input target string")

Dim StringArray(10) As String
    Dim Rnd As New Random()
    For i = 1 To 10
        StringArray(i) = GenerateString(Len(Target), Rnd)
        Debug.Print(StringArray(i))
    Next

 Function GenerateString(size As Integer, Rnd as Random) As String
    Dim LegalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    Dim Builder As New System.Text.StringBuilder()
    Dim Ch As Char

    For i As Integer = 0 To size - 1
        Ch = LegalCharacters(Rnd.Next(0, LegalCharacters.Length))
        Builder.Append(Ch)
    Next

    Return Builder.ToString()
End Function

Upvotes: 1

Related Questions