2016-11-16 46 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输出所需输出的一部分。希望这回答你的问题。