DEV Community

loading...
Cover image for How to generate permutations in JavaScript?

How to generate permutations in JavaScript?

gkucmierz profile image Grzegorz Kućmierz ・1 min read

Generating permutations is pretty common problem in many algorithmic problems.

I have already implemented this problem, so you can find it in my github in algorithms repo.

Here you have function that is generating permutations from Set of specified size.
https://github.com/gkucmierz/algorithms/blob/master/js/generate_permutations.js

So if you pass 3 to it you will get this 2d array:

console.log(genPermutations(3));

[
  [
    0,
    1,
    2
  ],
  [
    0,
    2,
    1
  ],
  [
    1,
    0,
    2
  ],
  [
    1,
    2,
    0
  ],
  [
    2,
    0,
    1
  ],
  [
    2,
    1,
    0
  ]
]

Subarrays are indexed from 0 to 2, so you can very easily adapt it to your code using these indexes.

const map = ['a', 'b', 'c'];

console.log(
  genPermutations(3)
    .map(permutation => {
      return permutation.map(idx => map[idx]).join('')
    })
);

[
  'abc',
  'acb',
  'bac',
  'bca',
  'cab',
  'cba'
]

Discussion

pic
Editor guide