/**
* Generate all permutations of an array using recursion.
*/
function generatePermutations<T>(arr: T[]): T[][] {
// Validate input
if (!Array.isArray(arr)) {
throw new Error("Input must be an array.");
}
const results: T[][] = [];
/**
* Recursive function to build permutations.
*/
function backtrack(current: T[], remaining: T[]) {
if (remaining.length === 0) {
results.push([...current]); // Push a copy of the current permutation
return;
}
for (let i = 0; i < remaining.length; i++) {
const next = remaining[i];
const newRemaining = [...remaining.slice(0, i), ...remaining.slice(i + 1)];
current.push(next);
backtrack(current, newRemaining);
current.pop(); // Backtrack
}
}
backtrack([], arr);
return results;
}
try {
const input: number[] = [1, 2, 3];
const permutations: number[][] = generatePermutations(input);
console.log(`All permutations of [${input}]:`);
permutations.forEach(p => console.log(p));
} catch (error) {
console.error("Error:", (error as Error).message);
}
/*
run:
"All permutations of [1,2,3]:"
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
*/