繁体   English   中英

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

[英]Creating a loop to check for cycles in a permutation

我的作业分配让我检查用户输入的数字中所有可能的周期符号。 我已经将输入发送到数组中,但是我不确定如何开始循环。 如何编辑此循环以使相同的数字显示不超过一次? 抱歉,如果格式不正确,请首次发布。

// example of user input
var permutation = [ 9,2,3,7,4,1,8,6,5 ] ;   

// add zero to match index with numbers
permutation.unshift(0) ;

// loop to check for all possible permutations
for (var i = 1; i < permutation.length -1; i++)
{
    var cycle = [];
    var currentIndex = i ;
    if ( permutation [ currentIndex ] == i )
        cycle.push(permutation [currentIndex]);
    while ( permutation [ currentIndex ] !== i )
    {
        cycle.push( permutation [currentIndex]);
        currentIndex = permutation [ currentIndex ] ;
    }

    // display in console
    console.log(cycle);
}

在这里回答了类似的问题。 这个想法是使用递归函数。
这是一个示例:

 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); } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM