Is there a way to generate all binary possibilities given a number N>=2,073,600 representing the size of the binary number?

Viewed 75

For example: N=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.

1 Answers

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));

Related