Identifying Array Permutations in JavaScript
To calculate all permutations of an array of integers, there are nuances to consider when adapting string-based algorithms to work on arrays.
The original function (designed for strings) tracks characters through chars and usedChars arrays. It iterates through each character, adding it to usedChars and recursively calling permute on the remaining characters.
Adapting to Integers
To accommodate arrays of integers, modifications are necessary:
Revised Function for Arrays
The revised function below addresses the aforementioned adaptations:
function permute(inputArr) { const permArr = []; const usedInts = []; for (let i = 0; i < inputArr.length; i++) { const el = inputArr.splice(i, 1); usedInts.push(el); if (inputArr.length === 0) { permArr.push(usedInts.slice()); } permute(inputArr.slice()); inputArr.splice(i, 0, el); usedInts.pop(); } return permArr; }
Usage Examples
Using the revised function, we can calculate permutations for arrays of integers:
console.log(permute([1, 2, 3, 4])); // [[1, 2, 3, 4], [1, 2, 4, 3], ...] console.log(permute([5, 6, 7])); // [[5, 6, 7], [5, 7, 6], ...]
The above is the detailed content of How Can I Efficiently Generate All Permutations of an Integer Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!