2016-11-03 92 views
2

我的家庭作业让我检查用户输入的数字中所有可能的循环记号。我有输入发送到一个数组,但我不知道如何开始循环。我怎样才能编辑这个循环,不会多次显示相同的数字?对不起,如果这是不正确的格式,第一次发布。创建一个循环来检查排列中的循环

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

什么是你的榜样输入您预期的输出?会不会是'[1,9,5,4,7,8,6] [2] [3]'?如果是这样,您可以在迭代时使用一组或一组布尔值来跟踪每个索引的“访问”数字。 –

回答

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