Permutations in JavaScript?

前端 未结 30 2659
不思量自难忘°
不思量自难忘° 2020-11-21 06:52

I\'m trying to write a function that does the following:

  • takes an array of integers as an argument (e.g. [1,2,3,4])
  • creates an array of all the possib
30条回答
  •  孤独总比滥情好
    2020-11-21 07:16

    Some version inspired from Haskell:

    perms [] = [[]]
    perms xs = [ x:ps | x <- xs , ps <- perms ( xs\\[x] ) ]
    

    function perms(xs) {
      if (!xs.length) return [[]];
      return xs.flatMap(x => {
        // get permutations of xs without x, then prepend x to each
        return perms(xs.filter(v => v!==x)).map(vs => [x, ...vs]);
      });
    }
    document.write(JSON.stringify(perms([1,2,3])));

提交回复
热议问题