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

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

Mary-Kate Olsen
Release: 2024-12-14 11:30:12
Original
729 people have browsed it

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

Identifying Array Permutations in JavaScript

To calculate all permutations of an array of integers, there are nuances to consider when adapting string-based algorithms to work on arrays.

The original function (designed for strings) tracks characters through chars and usedChars arrays. It iterates through each character, adding it to usedChars and recursively calling permute on the remaining characters.

Adapting to Integers

To accommodate arrays of integers, modifications are necessary:

  1. Integer Tracking: Replace chars and usedChars with integer arrays to track elements.
  2. Splicing and Concatenation: Use splice and concat to manipulate the integer array instead of strings.
  3. Splitting and Joining: Remove the string splitting and joining operations since they are not applicable to integers.

Revised Function for Arrays

The revised function below addresses the aforementioned adaptations:

function permute(inputArr) {
    const permArr = [];
    const usedInts = [];

    for (let i = 0; i < inputArr.length; i++) {
        const el = inputArr.splice(i, 1);
        usedInts.push(el);
        if (inputArr.length === 0) {
            permArr.push(usedInts.slice());
        }
        permute(inputArr.slice());
        inputArr.splice(i, 0, el);
        usedInts.pop();
    }

    return permArr;
}
Copy after login

Usage Examples

Using the revised function, we can calculate permutations for arrays of integers:

console.log(permute([1, 2, 3, 4])); // [[1, 2, 3, 4], [1, 2, 4, 3], ...]

console.log(permute([5, 6, 7])); // [[5, 6, 7], [5, 7, 6], ...]
Copy after login

The above is the detailed content of How Can I Efficiently 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