创建循环以检查排列中的循环

时间:2016-11-03 00:37:25

标签: javascript arrays permutation

我的家庭作业让我从用户输入的号码中检查所有可能的周期符号。我将输入发送到数组但我不知道如何启动循环。如何编辑此循环以不多次显示相同的数字?对不起,如果这不是正确的格式,第一次发布。

AT#SD=1,0,80,httpbin.org

POST /login HTTP/1.1
Host: httpbin.org
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Content-Length: 9

test=test

1 个答案:

答案 0 :(得分:0)

我回答了类似的问题here。这个想法是使用递归函数。
这是一个样本:



var array = ['a', 'b', 'c'];
var counter = 0; //This is to count the number of arrangement possibilities

permutation();
console.log('Possible arrangements: ' + counter); //Prints the number of possibilities

function permutation(startWith){
    startWith = startWith || '';
    for (let i = 0; i < array.length; i++){
        //If the current character is not used in 'startWith'
        if (startWith.search(array[i]) == -1){
            
                
            //If this is one of the arrangement posibilities
            if ((startWith + array[i]).length == array.length){
                counter++;
                console.log(startWith + array[i]); //Prints the string in console
            }
                
            //If the console gives you "Maximum call stack size exceeded" error
            //use 'asyncPermutation' instead
            //but it might not give you the desire output
            //asyncPermutation(startWith + array[i]);
            permutation(startWith + array[i]); //Runs the same function again
        }
        else { 
            continue; //Skip every line of codes below and continue with the next iteration
        } 
    }
    function asyncPermutation(input){
        setTimeout(function(){permutation(input);},0);
    }
 }
&#13;
&#13;
&#13;