Permutations in JavaScript?

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

    I had a crack at making a version of this that attempts to be concise yet readable, and purely functional programming.

    function stringPermutations ([...input]) {
      if (input.length === 1) return input;
    
      return input
        .map((thisChar, index) => {
          const remainingChars = [...input.slice(0, index), ...input.slice(index + 1)];
          return stringPermutations(remainingChars)
            .map(remainder => thisChar + remainder);
        })
        .reduce((acc, cur) => [...acc, ...cur]);
    }
    

    Note that the argument formatting turns an input string into an array. Not sure if that's a bit too magical.. Not sure I've seen it in the wild. For real readability I'd probably instead do input = [...input] for the first line of the function.

提交回复
热议问题