DEV Community

Cover image for How to generate permutations in JavaScript?
Grzegorz Kućmierz
Grzegorz Kućmierz

Posted on

How to generate permutations in JavaScript?

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
  ]
]
Enter fullscreen mode Exit fullscreen mode

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'
]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)