JavaScript - Generating combinations from n arrays with m elements

前端 未结 10 1787
一个人的身影
一个人的身影 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:46

    After doing a little research I discovered a previous related question: Finding All Combinations of JavaScript array values

    I've adapted some of the code from there so that it returns an array of arrays containing all of the permutations:

    function(arraysToCombine) {
        var divisors = [];
        for (var i = arraysToCombine.length - 1; i >= 0; i--) {
           divisors[i] = divisors[i + 1] ? divisors[i + 1] * arraysToCombine[i + 1].length : 1;
        }
    
        function getPermutation(n, arraysToCombine) {
           var result = [], 
               curArray;    
           for (var i = 0; i < arraysToCombine.length; i++) {
              curArray = arraysToCombine[i];
              result.push(curArray[Math.floor(n / divisors[i]) % curArray.length]);
           }    
           return result;
        }
    
        var numPerms = arraysToCombine[0].length;
        for(var i = 1; i < arraysToCombine.length; i++) {
            numPerms *= arraysToCombine[i].length;
        }
    
        var combinations = [];
        for(var i = 0; i < numPerms; i++) {
            combinations.push(getPermutation(i, arraysToCombine));
        }
        return combinations;
    }
    

    I've put a working copy at http://jsfiddle.net/7EakX/ that takes the array you gave earlier ([[0,1], [0,1,2,3], [0,1,2]]) and outputs the result to the browser console.

提交回复
热议问题