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

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

Susan Sarandon
Release: 2024-12-19 19:56:12
Original
164 people have browsed it

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

Permutation Generation in JavaScript

To generate permutations of an array of integers in JavaScript, a recursive function can be employed. The aim is to take an integer array as input, and return an array containing all possible permutations, each with the same length as the input array.

Modified Permutation Function

The provided function for string permutation can be modified by considering the differences in how methods operate on integers and strings:

const permArr = [];
const usedNums = [];

function permuteIntegers(input) {
  for (let i = 0; i < input.length; i++) {
    const num = input.splice(i, 1)[0];
    usedNums.push(num);
    if (input.length === 0) {
      permArr.push([...usedNums]);
    }
    permuteIntegers(input);
    input.splice(i, 0, num);
    usedNums.pop();
  }
  return permArr;
}
Copy after login

Shorter and Modern Version (ES6)

Using modern JavaScript features, the above function can be simplified:

const permutator = (inputArr) => {
  const result = [];

  const permute = (arr, memo = []) => {
    if (arr.length === 0) {
      result.push(memo);
    } else {
      for (let i = 0; i < arr.length; i++) {
        const curr = arr.slice();
        const next = curr.splice(i, 1)[0];
        permute(curr, memo.concat(next));
      }
    }
  };

  permute(inputArr);
  return result;
};
Copy after login

Usage Examples

Both functions can be used to generate permutations of integer arrays:

console.log(permuteIntegers([1, 2, 3])); // Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

console.log(permutator([1, 2, 3])); // Output: same as above
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template