Permutations in JavaScript?

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

    I wrote a post to demonstrate how to permute an array in JavaScript. Here is the code which does this.

    var count=0;
    function permute(pre,cur){ 
        var len=cur.length;
        for(var i=0;i1){
                permute(p,c);
            }else{
                print(p);
                count++;
            }
        }
    }
    function print(arr){
        var len=arr.length;
        for(var i=0;i");
    }
    function remove(arr,item){
        if(contains(arr,item)){
            var len=arr.length;
            for(var i = len-1; i >= 0; i--){ // STEP 1
                if(arr[i] == item){             // STEP 2
                    arr.splice(i,1);              // STEP 3
                }
            }
        }
    }
    function contains(arr,value){
        for(var i=0;i

    Just call

    permute([], [1,2,3,4])

    will work. For details on how this works, please refer to the explanation in that post.

提交回复
热议问题