创建一个循环来检查排列中的循环

2023-12-21

我的家庭作业让我检查用户输入的数字中所有可能的循环符号。我已将输入发送到数组中,但我不确定如何启动循环。我如何编辑此循环以不多次显示相同的数字?第一次发帖,格式不对,请见谅。

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

我回答过类似的问题here https://stackoverflow.com/questions/40623774/array-arrangement-permutation/40625585#40625585。这个想法是使用递归函数。
这是一个示例:

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);
    }
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建一个循环来检查排列中的循环 的相关文章

随机推荐