配列の配列の可能性を順番に見つける方法を探しています。私はそれらを順次追加することだけを気にし、スキップやシャッフルの値は必要ありません。配列の並べ替え
例:
var array = [a, b, c, d, e, f];
所望の出力:
a
ab
abc
abcd
abcde
abcdef
それは私が各可能な出力で計算を行うことができますので、ループの内側にあることが必要です。
配列の配列の可能性を順番に見つける方法を探しています。私はそれらを順次追加することだけを気にし、スキップやシャッフルの値は必要ありません。配列の並べ替え
例:
var array = [a, b, c, d, e, f];
所望の出力:
a
ab
abc
abcd
abcde
abcdef
それは私が各可能な出力で計算を行うことができますので、ループの内側にあることが必要です。
あなたは一度、各文字を反復処理する可能性があり、全配列を移入することができるはずです。
あなたができることは次のとおりです。
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);
アレイを現在のインデックスにスライスすることで、アレイを簡単に縮小できます。
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])
}
あなたはこれを行うには、再帰関数が必要です。
あなたの配列の配列の可能性は6です! (これは720です)、私はサンプルの結果を短くするために3に短縮し、可能な配列の数を3にします!
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);
}
}
(6)第3の出力は、希望の出力の一部です。希望があなたの質問に答えることを望みます。
a、b、cとは何ですか?変数?文字列?糸くずの部分? –
それはすべての望ましい出力ですか?キャラクターは別の順序ではどうですか? – derp