Permutations in JavaScript?

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

    Here is a minimal ES6 version. The flatten and without functions can be pulled from Lodash.

    const flatten = xs =>
        xs.reduce((cum, next) => [...cum, ...next], []);
    
    const without = (xs, x) =>
        xs.filter(y => y !== x);
    
    const permutations = xs =>
        flatten(xs.map(x =>
            xs.length < 2
                ? [xs]
                : permutations(without(xs, x)).map(perm => [x, ...perm])
        ));
    

    Result:

    permutations([1,2,3])
    // [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
    

提交回复
热议问题