Camkode
Camkode

Find all Permutations in JavaScript

Posted by Kosal

Find all Permutations in JavaScript

Generate all permutations of string and filter unique string by using JavaScript

An example of permutations of string would be this:

B[123]--> C[132]--> D[213]--> E[231]--> F[312]--> G[321]-->

So we’ve figured out what a permutation is, and established that (depending on the length of the string) we may be looking for a lot of them.

Below is the function to generate permutations:

const findPermutation = (num) => {
  const results = []
  const num_data = num.split('')
  function permute(arr, mem) {
    let cur
    const tmp = mem || []

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

    return results
  }
  return permute(num_data)
    .map((t) => t.join(''))
    .filter((value, index, self) => self.indexOf(value) === index)
}

Example:

findPermutation('123');
[ '123', '132', '213', '231', '312', '321' ]

findPermutation('abcd');
[
  'abcd', 'abdc', 'acbd',
  'acdb', 'adbc', 'adcb',
  'bacd', 'badc', 'bcad',
  'bcda', 'bdac', 'bdca',
  'cabd', 'cadb', 'cbad',
  'cbda', 'cdab', 'cdba',
  'dabc', 'dacb', 'dbac',
  'dbca', 'dcab', 'dcba'
]

findPermutation('aabc');
[
  'aabc', 'aacb',
  'abac', 'abca',
  'acab', 'acba',
  'baac', 'baca',
  'bcaa', 'caab',
  'caba', 'cbaa'
]

Hope this article can help you.