Permutations in JavaScript?

前端 未结 30 2737
不思量自难忘°
不思量自难忘° 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条回答
  •  旧时难觅i
    2020-11-21 07:08

    Similar in spirit to the Haskell-style solution by @crl, but working with reduce:

    function permutations( base ) {
      if (base.length == 0) return [[]]
      return permutations( base.slice(1) ).reduce( function(acc,perm) {
        return acc.concat( base.map( function(e,pos) {
          var new_perm = perm.slice()
          new_perm.splice(pos,0,base[0])
          return new_perm
        }))
      },[])    
    }
    

提交回复
热议问题