how to see all permutations of array code example
Example 1: how to find all permutations of an array with javascript
function getArrayMutations(arr, perms = [], len = arr.length) {
if (len === 1) perms.push(arr.slice(0))
for (let i = 0; i < len; i++) {
getArrayMutations(arr, perms, len - 1)
len % 2
? [arr[0], arr[len - 1]] = [arr[len - 1], arr[0]]
: [arr[i], arr[len - 1]] = [arr[len - 1], arr[i]]
}
return perms
}
Example 2: find all permutations of a string
void permute(string a, int l, int r)
{
if (l == r)
cout<<a<<endl;
else
{
for (int i = l; i <= r; i++)
{
swap(a[l], a[i]);
permute(a, l+1, r);
swap(a[l], a[i]);
}
}
}