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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 01:31:11527browse

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

Permutations in JavaScript

When faced with the task of generating permutations for an array of integers, the straightforward approach involves a recursive algorithm. One such algorithm, designed to handle strings, is presented in the given code snippet. However, when attempting to adapt this algorithm to work with an array of integers, challenges arise due to differences in how methods operate on different data types.

To address this issue, a modified version of the algorithm is required, which takes into account the specific behaviors of integers. One elegant solution, presented below, incorporates these considerations:

function permutator(inputArr) {
  var results = [];

  function permute(arr, memo) {
    var cur, memo = memo || [];

    for (var i = 0; i < arr.length; i++) {
      cur = arr.splice(i, 1);
      if (arr.length === 0) {
        results.push(memo.concat(cur));
      }
      permute(arr.slice(), memo.concat(cur));
      arr.splice(i, 0, cur[0]);
    }

    return results;
  }

  return permute(inputArr);
}

This algorithm operates on a copy of the input array, ensuring that the original array remains unchanged. It recursively explores all possible combinations and stores the permutations in an array of arrays.

Alternatively, an ES6 (2015) version of this algorithm is also available:

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

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

  permute(inputArr)

  return result;
}

This version employs arrow functions and default parameter values for a more concise syntax. The functionality remains the same, generating permutations for the provided array.

The above is the detailed content of How Can I Generate Permutations of an Integer Array 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