ShuffleLetters

PROKA

Junior Contributor
Joined
Sep 3, 2003
Messages
249
Location
Bucharest
I wrote a function to shuffle the letters in a word, but ... it doesn't work and I don't know why :-\
Code:
Public Function ShuffleLetters(ByVal text As String) As String
        While i < Len(text)
again:
            Randomize()
            Random = CInt(Int((Len(text) * Rnd()) + 1))
            If pos(Random) = False Then
                LetterToshuffle = Mid(text, Random, 1)
                ShuffleLetters += LetterToshuffle
                pos(Random) = True
                i += 1
            Else : GoTo again
            End If

        End While
    End Function
 
Sounds a bit like a homework question but, firstly how doesn't it work? Errors? invalid results?
You are also using a lot of VB6 compatability functions Len, Mid etc
Len(text) would be better as text.Length for example.

Also
CInt(Int((Len(text) * Rnd()) + 1))

seems to be multiplying a long by a single, converting to an integer and then casting that integer to an integer - is that really necessary?
 
Ok I re-wrote the function

STILL IT DOESN"T WORK
no error but ... it does nothing it idles ... then the program freezes

Code:
    Public Function Shuffle(ByVal textus As String) As String
        Shuffle = ""
        While Len(Shuffle) < Len(textus)
            Randomize()
            random = CInt(Int(((Len(textus) - 1) * Rnd())) + 1)
            If pos(random) = False Then
                Shuffle += Mid(textus, random, 1)
                pos(random) = True
            End If
        End While


    End Function
 
It is rather a cumbersome method you are using there. A much more efficient method would be to remove the character from the original string when adding it to the shuffled string:

Visual Basic:
    Public Function Scramble(ByVal textus As String) As String
        Static rand As New Random()

        Dim result As String
        Dim i As Integer
        Dim pos As Integer

        For i = 1 To textus.Length
            pos = rand.Next(0, textus.Length - 1)
            result += textus.Substring(pos, 1)
            If (pos) Then
                textus = textus.Substring(0, pos) + textus.Substring(pos + 1)
            Else
                textus = textus.Substring(1)
            End If
        Next

        Return result
    End Function
 
Back
Top