简体   繁体   中英

How to print all combinations of M x N binary matrix in JavaScript

Im working on a function that takes the dimensions of a matrix and runs through every possible binary matrix given those dimensions. I'm doing it recursively and plan on implementing it using DP later for better performance. Heres my attempt which doesn't work. Warning the fill function is an ES6 function I believe. JSFiddle here.

var printAllBinMatsAux = function(m, n, r, c, mat) {
    console.log(mat);
    if (r >= m) return;
    if (c === n - 1) {
        return printAllBinMatsAux(m, n, r + 1, 0, mat.slice());
    }

    printAllBinMatsAux(m, n, r, c + 1, mat.slice());
    mat[r][c] = 1;
    printAllBinMatsAux(m, n, r, c + 1, mat.slice());
}

var printAllBinMats = function(m, n) {
    var mat = [];
    for (var i = 0; i < m; i++) {
        var row = new Array(n).fill(0);
        mat.push(row);
    }
    printAllBinMatsAux(m, n, 0, 0, mat);
}

printAllBinMats(3, 4);

If your dimensions aren't going to be too big, then I'd 'binary count' a 1d array with length m*n. You can then split it into rows. Not sure on performance but it does 3x4 pretty fast for me. Codepen here

function matrices(m, n) {
  var mn = m*n,
      loopTo = Math.pow(2, mn);

  for (var i = 0; i < loopTo; i++) {
    var matrix = [];
    for (var j = 0; j < mn; j++) {
      matrix.push((i & (1 << j)) ? 1 : 0);
    }
    print(matrix, m, n);
  }
}

function print(matrix, m, n) {
  var output = '';
  // Split the single array into m rows
  for (var i = 0; i < m; i++) {
    output += matrix.slice(i * n, (i+1) * n).join(' ') + '\n';
  }
  out.innerText += output + '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM