Permutations in JavaScript?

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

    function nPr(xs, r) {
        if (!r) return [];
        return xs.reduce(function(memo, cur, i) {
            var others  = xs.slice(0,i).concat(xs.slice(i+1)),
                perms   = nPr(others, r-1),
                newElms = !perms.length ? [[cur]] :
                          perms.map(function(perm) { return [cur].concat(perm) });
            return memo.concat(newElms);
        }, []);
    }
    

提交回复
热议问题