ellessuom
5/13/2018 - 9:23 PM

Recursive function to create a cartesian product from a 2D matrix

Recursive function to create a cartesian product from a 2D matrix

const cartesianProduct = matrix => {
    let indexes = new Array(matrix.length).fill(0),
        output  = [];

    let f = function (ic, ie) {
        if (ic < 0) {
            return;
        }
        if (ie >= matrix[ic].length) {
            return f(ic - 1, indexes[ic - 1] + 1);
        } else {
            indexes[ic] = ie;
        }
        if (ic + 1 <= matrix.length - 1) {
            f(ic + 1, 0);
        } else {
            output.push(_.map(indexes, function (ind, i) {
                return matrix[i][ind];
            }));
            if (indexes[ic] + 1 < matrix[ic].length) {
                f(ic, indexes[ic] + 1);
            } else if (ic - 1 >= 0) {
                indexes[ic] = 0;
                f(ic - 1, indexes[ic - 1] + 1);
            }
        }
    };
    
    const init = () => f(0, 0);
    init();
};