Permutations in JavaScript?

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

    Here's one I made...

    const permute = (ar) =>
      ar.length === 1 ? ar : ar.reduce( (ac,_,i) =>
        {permute([...ar.slice(0,i),...ar.slice(i+1)]).map(v=>ac.push([].concat(ar[i],v))); return ac;},[]);
    

    And here it is again but written less tersely!...

    function permute(inputArray) {
      if (inputArray.length === 1) return inputArray;
      return inputArray.reduce( function(accumulator,_,index){
        permute([...inputArray.slice(0,index),...inputArray.slice(index+1)])
          .map(value=>accumulator.push([].concat(inputArray[index],value)));
        return accumulator;
      },[]);
    }
    

    How it works: If the array is longer than one element it steps through each element and concatenates it with a recursive call to itself with the remaining elements as it's argument. It doesn't mutate the original array.

提交回复
热议问题