生成字符串的所有组合的函数

时间:2017-01-25 18:32:08

标签: javascript

我是javascript的新手,仍在尝试学习东西 我找到了一个关于函数问题的解决方案,该函数应该生成字符串中字符的所有组合。

我想弄清楚:

  • 循环内发生了什么?
  • 循环如何逐步执行?
    我无法弄清楚它是如何达到最终输出的。

我试了很长时间才搞清楚,但我不确定那些内部会发生什么    循环。我不明白它是如何得到的" ab"," ac"。 ......一起    在最终输出中,arrTemp推送result [x]和char。我看到结果数组最初是空的,然后与arrTemp连接。

以下是我挣扎的代码:

 function combString(str){
     var lenStr = str.length;
     var result = [];
     var indexCurrent = 0;

     while(indexCurrent < lenStr){
         var char = str.charAt(indexCurrent);
         var x;
         var arrTemp = [char];

         for(x in result) {
             arrTemp.push(""+result[x]+char);
         }
         result = result.concat(arrTemp);

         indexCurrent++;
     }

     return result;
}

console.log(combString("abc"));

这是输出

["a", "b", "ab", "c", "ac", "bc", "abc"]

5 个答案:

答案 0 :(得分:3)

我们可以简单地通过使用“切片”来实现它。

function combinator (s) {
   list_of_strings = new Array();
   for(i=0;i<s.length;i++) {
       for(j=i+1;j<s.length+1;j++) {
           list_of_strings.push(s.slice(i, j));
       }
   }
   return list_of_strings;
}

document.write(combinator("dog"));

答案 1 :(得分:0)

以下是注释代码,希望它能帮助您理解!

function combString(str) {
    //String length
    var lenStr = str.length;
    //Initially empty, where the results will be stored
    var result = [];
    //Currently selected letter
    var indexCurrent = 0;

    //Looping from 0 to the length of the string
    //var char is selecting the character at this index. Ex: "a", then "b", then "c"
    while (indexCurrent < lenStr) {
        //Get the character at the index position. 
        var char = str.charAt(indexCurrent);

        var x;
        var arrTemp = [char];
        //For each previous result
        for (x in result) {
            //Add the current character to the index

            arrTemp.push("" + result[x] + char);

            /*
             * Ex: "abc"
             * First round: result is empty, so this code doesn't execute
             * Second round: result contains "a". Adds "ab" to the result array
             *  - Then. result array will contain "a","b" and "ab"
             * Third round: result contains "a","b","ab"
             *     For all of these results, add "c" to the resulting array
             *     Ex: "ac","bc", "abc"
             *  - Then add "c"
             */
        }
        result = result.concat(arrTemp);

        //Increment the current index to go to the next character 
        indexCurrent++;
    }

    return result;
}

console.log(combString("abc"));

答案 2 :(得分:0)

我们假设输入是“ab”。以下是没有循环的函数的工作方式:

var str = "ab";

var lenStr = str.length;
var result = [];
var indexCurrent = 0;

var char, x, arrTemp;

//first while iteration begins

//indexCurrent === 0
//so char becomes "a"
char = str.charAt(indexCurrent);

//A temp array is created so it can be concatenated to the results array.
arrTemp = [char];
//arrTemp == ["a"]

//for-loop here, but since the result array is empty, it wont execute

//result becomes ["a"]
result = result.concat(arrTemp);

//indexCurrent becomes 1
indexCurrent++;

//second while iteration begins

//indexCurrent === 1
//so char becomes "b"
char = str.charAt(indexCurrent);

arrTemp = [char];
//arrTemp == ["b"]

//For-loop begins, x === 0  
//result[x] is the xth (in this case, first) value of the result-array
//the double quotes cast the result as string  
//in other words, it says:
//"store at the end of the array arrTemp, as string, the value from index x
//in the array result, plus the character stored in the variable char"
arrTemp.push(""+result[x]+char);

//arrTemp is now ["b", "ab"]

//result only has one item, so for-loop ends

//result becomes ["a", "b", "ab"]
result = result.concat(arrTemp);

//indexCurrent becomes 2
indexCurrent++;

//function returns result

请注意,for-in循环不应用于迭代数组(请参阅here)。

答案 3 :(得分:0)

好的,非常简单的我会为你评论代码,然后我将展示用简单的字符串示例做的事情:

function combString(str){
 var lenStr = str.length;
 var result = [];
 var indexCurrent = 0;

 while(indexCurrent < lenStr){ // repeat until indexCurrent equals lenStr, the aim is to browse threw the string
     var char = str.charAt(indexCurrent); // select the char at indexCurrent
     var x;
     var arrTemp = [char];//put the selected char in an array

     for(x in result) {


    /*Here it's a little bit tricky, array are object, and actually
 the indexes of the array are properties which names are includes between 0 and
 2³²-2, but they can have other properties like any other object. that's 
the reason why you can use a for in loop here which will go threw the 
array and perform action on its properties with property name stored in the x variable (actually it is better to use a foreach loop) */


            arrTemp.push(""+result[x]+char); /* so here you concat the 
value of the current property of result (in the for in loop) with the char
 at indexCurrent and you add the concatenation result at the end of arrTemp */
     }
     result = result.concat(arrTemp); //here you concat result array and arrTemp and assign the concatenation result to result (I know there is a lot of result ahah)

     indexCurrent++; //and then you go to the next char in the string and you repeat 
 }
 // when the while loop ends you return result
 return result;

}

所以让我们看一下这个字符串的例子&#34; abc&#34;:

表示indexCurrent = 0:

result = [];
char = 'a';
arrayTemp (before for in loop)= ['a'];
arrayTemp (after for in loop)= ['a'];
result = ['a'];

表示indexCurrent = 1:

result = ['a'];
char = 'b';
arrayTemp (before for in loop) = ['b'];
arrayTemp (after for in loop) = ['b','ab']
result = ['a', 'b', 'ab'];

表示indexCurrent = 2:

result = ['a', 'b', 'ab'];
char = 'c';
arrayTemp (before for in loop) = ['c'];
arrayTemp (after for in loop) = ['c','ac','bc','abc']
result = ['a', 'b', 'ab','c','ac','bc','abc'];

我希望能帮到你

答案 4 :(得分:0)

简单地使用for循环和while语句来获得不同的组合。

function combu(s){
var buff = [];
var res = [];
for (i=0;i<s.length;i++){
    buff = [s[i]];
    var index=0;
    while(res[index]){
        buff.push(''+res[index]+s[i]);
        index++;
    }
    res = res.concat(buff);
}
return res;
}

combu('abc');