JavaScript - Generating combinations from n arrays with m elements

前端 未结 10 1597
一个人的身影
一个人的身影 2020-11-22 04:10

I\'m having trouble coming up with code to generate combinations from n number of arrays with m number of elements in them, in JavaScript. I\'ve seen similar questions about

10条回答
  •  不思量自难忘°
    2020-11-22 04:42

    var f = function(arr){
        if(typeof arr !== 'object'){
            return false;
        }
    
        arr = arr.filter(function(elem){ return (elem !== null); }); // remove empty elements - make sure length is correct
        var len = arr.length;
    
        var nextPerm = function(){ // increase the counter(s)
            var i = 0;
    
            while(i < len)
            {
                arr[i].counter++;
    
                if(arr[i].counter >= arr[i].length){
                    arr[i].counter = 0;
                    i++;
                }else{
                    return false;
                }
            }
    
            return true;
        };
    
        var getPerm = function(){ // get the current permutation
            var perm_arr = [];
    
            for(var i = 0; i < len; i++)
            {
                perm_arr.push(arr[i][arr[i].counter]);
            }
    
            return perm_arr;
        };
    
        var new_arr = [];
    
        for(var i = 0; i < len; i++) // set up a counter property inside the arrays
        {
            arr[i].counter = 0;
        }
    
        while(true)
        {
            new_arr.push(getPerm()); // add current permutation to the new array
    
            if(nextPerm() === true){ // get next permutation, if returns true, we got them all
                break;
            }
        }
    
        return new_arr;
    };
    

提交回复
热议问题