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);
}
あなたの例入力のためのあなたの予想出力は何ですか?それは '[1、9、5、4、7、8、6] [2] [3]'でしょうか?そうであれば、反復しながらインデックスごとにブーリアンのセットまたは配列で「訪問済み」の番号を追跡することができます。 –