/**
* Generate all permutations of an array using recursion and backtracking
*/
function getPermutations(arr) {
const results = [];
// Recursive function
function backtrack(startIndex) {
// if we've reached the end, store a copy of the array
if (startIndex === arr.length) {
results.push([...arr]);
return;
}
for (let i = startIndex; i < arr.length; i++) {
// Swap current index with the loop index
[arr[startIndex], arr[i]] = [arr[i], arr[startIndex]];
// Recurse for the next index
backtrack(startIndex + 1);
// Backtrack: swap back to restore original state
[arr[startIndex], arr[i]] = [arr[i], arr[startIndex]];
}
}
// Start recursion from index 0
backtrack(0);
return results;
}
try {
const arr = [1, 2, 3];
const permutations = getPermutations(arr);
console.log("All permutations:");
permutations.forEach(p => console.log(p));
} catch (error) {
console.error("Error generating permutations:", error.message);
}
/*
run:
All permutations:
[ 1, 2, 3 ]
[ 1, 3, 2 ]
[ 2, 1, 3 ]
[ 2, 3, 1 ]
[ 3, 2, 1 ]
[ 3, 1, 2 ]
*/