Permutations in JavaScript?

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

    This is a very nice use-case for map/reduce:

    function permutations(arr) {
        return (arr.length === 1) ? arr :
        arr.reduce((acc, cv, index) => {
            let remaining = [...arr];
            remaining.splice(index, 1);
            return acc.concat(permutations(remaining).map(a => [].concat(cv,a)));
        }, []);
    }
    
    • First, we handle the base case and simply return the array if there is only on item in it
    • In all other cases
      • we create an empty array
      • loop over the input-array
      • and add an array of the current value and all permutations of the remaining array [].concat(cv,a)

提交回复
热议问题