Permutation d'arrangement de tableau

Vous cherchez un moyen de trouver séquentiellement différentes possibilités d'arrangement d'un tableau. Je me soucie seulement de les ajouter séquentiellement, ne nécessite pas de sauter ou de mélanger des valeurs.

Exemple:

var array = [a, b, c, d, e, f]; 

Sortie souhaitée:

 a ab abc abcd abcde abcdef 

Il doit être à l'intérieur d'une boucle afin que je puisse effectuer un calcul avec chaque sortie possible.

Vous pourriez pouvoir localiser toutes les séquences sur chaque personnage.

Voici ce que vous pourriez faire.

 var inputArray = ['a', 'b', 'c', 'd', 'e', 'f']; var outputStrings = []; inputArray.forEach((item, idx) => { let prevString = (idx !== 0) ? outputStrings[idx - 1] : ""; outputStrings.push(prevString + item); }); console.log(outputStrings); 

Vous pouvez facilement réduire le tableau en tranchant le tableau à l'index actuel.

 var inputArray = ['a', 'b', 'c', 'd', 'e', 'f']; var outputArray = inputArray.reduce(function(result, item, index, arr) { return result.concat(arr.slice(0, index + 1).join('')); }, []); document.body.innerHTML = '<pre>' + outputArray.join('\n') + '</pre>'; 
 var array = ['a', 'b', 'c', 'd', 'e', 'f']; results = []; for (x = 1; x < array.length + 1; ++x) { results.push(array.slice(0, x).toString().replace(/,/g, "")) } //PRINT ALL RESULTS IN THE RESULTS VARIABLE for (x = 0; x < results.length; ++x) { console.log(results[x]) } 

Vous avez besoin d'une fonction récursive pour ce faire.
Puisque la quantité d'arrangement possible de votre gamme est de 6! (C'est-à-dire 720), je vais raccourcir à 3 pour raccourcir le résultat de l'échantillon, rends le nombre d'agencement possible à 3! (Qui est 6)

 var array = ['a', 'b', 'c']; var counter = 0; //This is to count the number of arrangement possibilities permutation(); console.log(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){ console.log(startWith + array[i]); //Print the string //If this is one of the arrangement posibilities if ((startWith + array[i]).length == array.length){ counter++; } //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]); } else { continue; //Skip every line of codes below and continue with the next iteration } } function asyncPermutation(input){ setTimeout(function(){permutation(input);},0); } }