如何通过每次删除4个字符来获取字符串的所有组合?

时间:2017-08-06 13:12:17

标签: javascript jquery string combinations

我试图在JavaScript中创建一个函数,对于给定的字符串,将通过删除输出所有可能的组合 每次只有4个字符串。如何输出所有组合?起始字符串的长度是动态的。谢谢。

**注意:**删除4个字符的顺序不应该是连续的

示例:

string:BmamdWRtaW51dGfVzZMI=  //B   m   a   m  d  W   R  t  a  W   5   1   d   G   f  V  z  Z  M  I  =
                             // 1   2   3   4  5  6   7  8  9  10  11  12  13  14  15 16 17 18 19 20 21

想要打印所有可能的组合:

 BmamdWRtaW51dGfVzZMI= (starting string)
-dWRtaW51dGfVzZMI=     (removed first 4 characters)
-BWRtaW51dGfVzZMI=     (removed 4 consecutive charaters start from 2th character)
-BmRtaW51dGfVzZMI=     (removed 4 consecutive charaters start from 3th character)
-BmataW51dGfVzZMI=     (removed 4 consecutive charaters start from 4th character)
-
-

2 个答案:

答案 0 :(得分:3)

假设n字符串str的长度

for (a=0; a<n-3; a++) {
    for (b=a+1; b<n-2; b++) {
        for (c=b+1; c<n-1; c++) {
            for (d=c+1; d<n; d++) {
                //delete the ath, bth, cth and dth charaters of the initial string
                result = str.substr(0, a)+str.substr(a+1, b-a-1)+str.substr(b+1, c-b-1)+str.substr(c+1, d-c-1)+str.substr(d+1);

                //and print the result
            }
        }
    }
}

答案 1 :(得分:0)

递归函数的一些伪代码:

myFunction (charactersRemoved, remainingString, previousString):

if charactersRemoved === 4 then echo previousString + remainingString
return

foreach character in remainingString
remainingString -= character
myFunction (charactersRemoved + 1, remainingString, previousString)
previousString += character
endfor

endfunction

myFunction(0, string, '')