This article mainly introduces how to implement permutation in JavaScript, which refers to the arrangement of elements in an array. For more information, see
Puzzles
Describe the arrangement of elements in an array.
Policy
Governance by subtraction and Recursion
JavaScript Solution
The Code is as follows:
/**
* Created by cshao on 12/23/14.
*/
Function getPermutation (arr ){
If (arr. length = 1 ){
Return [arr];
}
Var permutation = [];
For (var I = 0; I var firstEle = arr [I];
Var arrClone = arr. slice (0 );
ArrClone. splice (I, 1 );
Var childPermutation = getPermutation (arrClone );
For (var j = 0; j ChildPermutation [j]. unshift (firstEle );
}
Permutation = permutation. concat (childPermutation );
}
Return permutation;
}
Var permutation = getPermutation (['A', 'B', 'C']);
Console. dir (permutation );
Result
The Code is as follows:
[['A', 'B', 'C'],
['A', 'C', 'B'],
['B', 'A', 'C'],
['B', 'C', 'a'],
['C', 'A', 'B'],
['C', 'B', 'a']