随机重新排列单词中的字母

Randomly rearrange letters in a word

使用这个 SO 问题/答案作为起点:Splitting a single word into an array of the consituent letters

我有一段简单的代码来获取一个词并将该词拆分为单个字母:

<%
Dim word1, i
word1 = "particle"
For i = 1 To Len(word1)
    Response.Write "<p>" & Mid(word1, i, 1) & "</p>"
Next
%>

我想知道如何取一个单词(可变长度,而不是上面例子中的 8 个字符长的单词),并随机重新排列单词的字母 - 例如particle 可以是例如:

alpreict
lircpaet
ctelaipr
teapclir
raeitclp

这是我想要实现的示例:https://onlinerandomtools.com/shuffle-letters

然而,我意识到说起来容易做起来难。

我想知道是否有人对如何使用 Classic ASP 实现这一点有任何建议吗?

谢谢

这是一种方法:

Function ShuffleText(p_sText)
    Dim iLength
    Dim iIndex
    Dim iCounter
    Dim sLetter
    Dim sText
    Dim sShuffledText
    
    ' Copy text passed as parameter
    sText = p_sText
    
    ' Get text length
    iLength = Len(sText)
    
    For iCounter = iLength To 1 Step -1
        
        ' Get random index
        iIndex = 1 + Int(Rnd * (iCounter))
        
        ' Get character at that index
        sLetter = Mid(sText, iIndex, 1)
        
        ' Remove character from string
        sText = Left(sText, iIndex - 1) & Mid(sText, iIndex + 1)
        
        ' Add character to shuffled string
        sShuffledText = sShuffledText & sLetter
            
    Next

    ' Return shuffled text
    ShuffleText = sShuffledText
    
End Function

此代码在字符串中选择一个随机字符,将其删除并将其添加到打乱后的字符串中。它重复这个过程,直到它遍历所有字符。

可能有更有效的方法来做到这一点,首先随机化一个数字数组并将这些数字用作 iIndex,而无需操纵 sText 字符串。