替换字符串ArrayList中元素的字符

时间:2015-08-22 13:03:28

标签: vb.net

我有一个字符串的ArrayList,我试图根据MutationRate的可能性,在每个字符串中随机生成的位置替换一个字符。

    Dim NewGeneration As New ArrayList 'ArrayList of strings
    For i = 0 To Parents.Count - 1
        NewGeneration.Add(Parents(i))
    Next

    Dim MutationRate As Double = 0.02
    Dim RndNum As New Random()
    Dim MutationPosition As Integer
    Randomize()
    MutationPosition = Math.Ceiling(Rnd() * Len(Target))

    For i = 0 To NewGeneration.Count - 1
        If (Rnd() * 1) <= MutationRate Then
        'Replace character at MutationPosition in NewGeneration(i) with GenerateChar(RndNum As Random)
        End If
    Next

Function GenerateChar(RndNum As Random) As String
    Dim LegalCharacters As String = " abcdefghijklmopqrstuvwxyz"
    Dim Builder As New System.Text.StringBuilder()
    Dim Ch As Char

    Ch = LegalCharacters(RndNum.Next(0, LegalCharacters.Length))
    Builder.Append(Ch)

    Return Builder.ToString()
End Function

我只找到了替换指定字符的函数,而不是替换元素的特定位置。我可以用什么来解决这个问题?

编辑:

找到解决方案:

    For i = 0 To NewGeneration.Count - 1
        Dim MutationPosition1 As Integer
        Dim MutationPosition2 As Integer
        MutationPosition1 = Math.Ceiling(Rnd() * Len(Target))
        MutationPosition2 = Math.Ceiling(Rnd() * Len(Target))
        If (Rnd() * 1) <= MutationRate Then
            Dim Position1Char As String = GetChar(NewGeneration(i), MutationPosition1)
            NewGeneration(i) = NewGeneration(i).Replace(Position1Char, GenerateChar(RndNum))

            Dim Position2Char As String = GetChar(NewGeneration(i), MutationPosition2)
            NewGeneration(i) = NewGeneration(i).Replace(Position2Char, GenerateChar(RndNum))
        End If
    Next

0 个答案:

没有答案