DEV Community

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

Posted on

3 1

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)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay