2016-11-16 48 views
0

尋找一種方法來順序尋找陣列的不同排列可能性。我只關心順序添加它們,不需要跳過或洗牌值。陣列排列置換

實施例:

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

所需的輸出:

a 
ab 
abc 
abcd 
abcde 
abcdef 

它需要一個循環內,所以我可以做與每個可能的輸出的計算。

+1

什麼是a,b,c?變量?字符串?皮棉片? –

+0

是所有期望的輸出?那麼不同順序的字符呢? – derp

回答

1

你可以在每一個字符重複一次,應該能夠填充所有序列。

這是你可以做的。

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

0

您可以通過將數組切片到當前索引來輕鬆地減少數組。

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>';

注:我仍然不知道你意思 「找到一個陣列的不同佈置可能性」

0

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

0

你需要一個遞歸函數來做到這一點。
由於數組的可能排列量爲6! (720),我會縮短到3縮短樣本結果,使可能的排列數爲3! (這是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); 
 
    } 
 
}

前3輸出所需輸出的一部分。希望這回答你的問題。