Permutations in JavaScript?

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

    My first contribution to the site. Also, according to the tests that I have done, this code runs faster than all the other methods mentioned here before this date, of course it is minimal if there are few values, but the time increases exponentially when adding too many.

    function permutations(arr) {
        var finalArr = [];
        function iterator(arrayTaken, tree) {
            var temp;
            for (var i = 0; i < tree; i++) {
                temp = arrayTaken.slice();
                temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]);
                if (tree >= arr.length) {
                    finalArr.push(temp);
                } else {
                    iterator(temp, tree + 1);
                }
            }
        }
        iterator(arr, 1);
        return finalArr;
    };
    

提交回复
热议问题