Home > Net >  Is there a way to generate all binary possibilities given a number N representing the size of the bi
Is there a way to generate all binary possibilities given a number N representing the size of the bi

Time:09-22

For example: Size 3 would generate:

1- 0 0 0
2- 0 0 1
3- 0 1 0
4- 0 1 1
5- 1 0 0
6- 1 0 1
7- 1 1 0
8- 1 1 1

I need this to build a program that receives a real big matrix size (like 1920x1080) and starts to print a matrix based on the array (in this case of size 2,073,600) with all the zeros and ones updating as they are generated.

CodePudding user response:

Basically you want a loop from zero to 2 ^ size - 1, and each number in that range display it in base-2 format.

const matrix = (size) => {
  const out = [];
  const max = Math.pow(2, size);
  for (let i = 0; i < max; i  ) {
    out.push(`${i   1}: ${i.toString(2).padStart(size, '0')}`);
  }
  return out;
}

console.log(matrix(4));

CodePudding user response:

you can convert to binary and back using parseInt(x,2) and s.toString(2) so it's a matter of counting.

var digits = 4;

var start = "0".repeat(digits);
var end = "1".repeat(digits);
for (var i = parseInt(start, 2); i <= parseInt(end, 2); i  ) {
  console.log(("0".repeat(digits)   i.toString(2)).slice(-digits))
}

  • Related