2016-11-03 3 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); 
 
    } 
 
}

関連する問題