JavaScript - Generating combinations from n arrays with m elements

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

    Just for fun, here's a more functional variant of the solution in my first answer:

    function cartesian() {
        var r = [], args = Array.from(arguments);
        args.reduceRight(function(cont, factor, i) {
            return function(arr) {
                for (var j=0, l=factor.length; j

    Alternative, for full speed we can dynamically compile our own loops:

    function cartesian() {
        return (cartesian.cache[arguments.length] || cartesian.compile(arguments.length)).apply(null, arguments);
    }
    cartesian.cache = [];
    cartesian.compile = function compile(n) {
        var args = [],
            indent = "",
            up = "",
            down = "";
        for (var i=0; i

提交回复
热议问题