Skip to content

Permutations

permuteArray.js

js
const permuteArray = function (array) {
  if (array.length < 2) return [array];
  const permutations = [];

  for (let i = 0; i < array.length; i++) {
    const value = array[i];
    if (array.indexOf(value) !== i) continue;

    const slicedArray = [...array.slice(0, i), ...array.slice(i + 1, array.length)];
    for (const subPermutation of permuteArray(slicedArray)) {
      permutations.push([value, ...subPermutation]);
    }
  }

  return permutations;
};

permuteArray.spec.js

js
it("should returns permutations", () => {
  expect(permuteArray([1, 2, 3])).toEqual([
    [1, 2, 3],
    [1, 3, 2],
    [2, 1, 3],
    [2, 3, 1],
    [3, 1, 2],
    [3, 2, 1]
  ]);
});

permuteString.js

js
const permuteString = function (string) {
  if (string.length < 2) return [string];
  const permutations = [];

  for (let i = 0; i < string.length; i++) {
    const value = string[i];
    if (string.indexOf(value) !== i) continue;

    const slicedString = string.slice(0, i) + string.slice(i + 1, string.length);
    for (const subPermutation of permuteString(slicedString)) {
      permutations.push(value + subPermutation);
    }
  }

  return permutations;
};

permuteString.spec.js

js
it("should returns permutations", () => {
  expect(permuteString("ABC")).toEqual(["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]);
});

Released under the MIT License.