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

问题描述

以这样的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字符串。