Permutations in JavaScript?

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

    Here's a cool solution

    const rotations = ([l, ...ls], right=[]) =>
      l ? [[l, ...ls, ...right], ...rotations(ls, [...right, l])] : []
    
    const permutations = ([x, ...xs]) =>
      x ? permutations(xs).flatMap((p) => rotations([x, ...p])) : [[]]
      
    console.log(permutations("cat"))

提交回复
热议问题