Permutations in JavaScript?

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

       function perm(xs) {
           return xs.length === 0 ? [[]] : perm(xs.slice(1)).reduce(function (acc, ys) {
            for (var i = 0; i < xs.length; i++) {
              acc.push([].concat(ys.slice(0, i), xs[0], ys.slice(i)));
            }
            return acc;
          }, []);
        }
    

    Test it with:

    console.log(JSON.stringify(perm([1, 2, 3,4])));
    

提交回复
热议问题