Permutations in JavaScript?

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

    #!/usr/bin/env node
    "use strict";
    
    function perm(arr) {
        if(arr.length<2) return [arr];
        var res = [];
        arr.forEach(function(x, i) {
            perm(arr.slice(0,i).concat(arr.slice(i+1))).forEach(function(a) {
                res.push([x].concat(a));
            });
        });
        return res;
    }
    
    console.log(perm([1,2,3,4]));
    

提交回复
热议问题