Permutations in JavaScript?

前端 未结 30 3215
不思量自难忘°
不思量自难忘° 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:13

    Quite late. Still just in case if this helps anyone.

    function permute(arr) {
      if (arr.length == 1) return arr
    
      let res = arr.map((d, i) => permute([...arr.slice(0, i),...arr.slice(i + 1)])
                                  .map(v => [d,v].join(''))).flat()
    
      return res
    }
    
    console.log(permute([1,2,3,4]))

提交回复
热议问题