创建循环以检查排列中的循环 [英] Creating a loop to check for cycles in a permutation
本文介绍了创建循环以检查排列中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的作业分配了我从用户输入的数字中检查所有可能的循环符号.我已经将输入发送到数组中,但是我不确定如何开始循环.如何编辑此循环以使相同的数字显示不超过一次?抱歉,如果格式不正确,请首次发布.
My homework assignment has me check for all possible cycle notations from user inputted numbers. I have the input sent into an array but i'm not sure how to start the loop. How could I edit this loop to not display the same numbers more than once? Sorry if this isn't proper format, first time posting.
// 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);
}
推荐答案
我回答了类似的问题这里.这个想法是使用递归函数.
这里是一个示例:
I answered a similar question here. The idea is to use recursive functions.
Here's a sample:
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);
}
}
这篇关于创建循环以检查排列中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文