Home >Web Front-end >JS Tutorial >How Can I Generate All Permutations of an Array of Integers in JavaScript?

How Can I Generate All Permutations of an Array of Integers in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 13:45:12951browse

How Can I Generate All Permutations of an Array of Integers in JavaScript?

Permutations in JavaScript: Array of Integers

In JavaScript, a common task is to generate permutations of an array. Permutations involve arranging the elements of an array in all possible orders. Consider a function that takes an array of integers and returns an array of all possible permutations, where each permutation has the same length as the original array.

To modify the function provided, which operates on strings, to work with an array of integers, several modifications are necessary. First, the split method used to create an array of characters from a string cannot be applied directly to an array of integers. Instead, the array can be iterated over and each element can be pushed to a new array:

const integers = [...input];

Next, the join method used to concatenate characters in the string permutation cannot be used with integers. Instead, the concat method can be used to create a new array containing all the integers:

if (integers.length === 0) {
  permArr[permArr.length] = [...usedChars];
}

The rest of the function remains the same, and it will now generate all possible permutations of an array of integers and return them as an array of arrays:

let permArr = [];
let usedChars = [];

function permute(input) {
  const integers = [...input];
  for (let i = 0; i < integers.length; i++) {
    const ch = integers.splice(i, 1);
    usedChars.push(ch);
    if (integers.length === 0) {
      permArr[permArr.length] = [...usedChars];
    }
    permute(integers);
    integers.splice(i, 0, ch);
    usedChars.pop();
  }
  return permArr;
}

This modified function can generate permutations of arrays of integers and return them as an array of arrays, each containing a different permutation.

The above is the detailed content of How Can I Generate All Permutations of an Array of Integers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn