2

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
Community
  • 1
  • 1
oddoneout
  • 23
  • 5
  • I would avoid using `Rnd` for a variable name as this is another function that produces a random value and so it could lead to strange compilation errors – Matt Wilko Aug 21 '15 at 15:52

1 Answers1

1

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
GeorgDangl
  • 2,146
  • 1
  • 29
  • 37