how to find all permutations of an array with javascript 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 // parity dependent adjacent elements swap
      ? [arr[0], arr[len - 1]] = [arr[len - 1], arr[0]]
      : [arr[i], arr[len - 1]] = [arr[len - 1], arr[i]]
  }

  return perms
}

Here is what the above code is Doing:
1. If the length of the array is 1, we push the array into the perms array.
2. We loop through the array and swap the first element with the last element.
3. We call the function again with the length of the array minus 1.
4. We repeat the process until the length of the array is 1.

Similar Posts