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

Смежные вопросы