Count Sets of 1s and 0s in a Binary Matrix



Counting sets of 1s and 0s in a binary matrix can be achieved using nested for loop with conditional statement. A binary matrix is a matrix that consists of only two digits as its name suggests and those two digits are 1 and 0.

In this article, we are having a 2D binary matrix having 0 and 1 only. Our task is to write a JavaScript program for counting the sets of 1s and 0s in a given binary matrix.

Formula:

Let us a consider a set as {a,b} having 2 elements i.e, n = 2.
Total number of subsets: 2^n | ({}, {a}, {b}, {a,b})
Total number of non-empty subsets: 2^n - 1 | ({a}, {b}, {a,b})

Example

Input:
arr = [[1, 0, 1], [0, 1, 0]]

row 1: [1, 0, 1]
ones = 2, zeroes = 1
For ones: 2^2 - 1 = 3
For zeroes: 2^1 - 1 = 1
ans = 3 + 1 = 4
Similarly, for row 2: ans = 4

Column 1: [1, 0]
ones = 1, zeroes = 1
For ones: 2^1 - 1 = 1, For zeroes: 2^1 - 1 = 1
ans = 1 + 1 = 2
Similarly, for column 2: ans = 2, for column 3: ans = 2

ans = (4 + 4 + 2 + 2 + 2) - (2 * 3) = 8

Output: 8

Steps to Count sets of 1s and 0s in binary matrix

  • We have declared a 2D array and defined a function fun() which accepts arr as its argument.
  • Inside function fun(), we have declared a variable ans in which we store the final count of the set of 1s and 0s.
  • We have used two nested for loop where first nested for loop count the set row wise and the second nested for loop count the set column wise.
  • We have used the if/else statement to increase the count of 1 and 0. The counts of 1s and 0s are stored in variables ones and zeroes respectively.
  • Then we have used Math.pow() function which calculates the number of non-empty subsets of all 1s and 0s.
  • At the end, we have subtracted the product of rows and columns to remove the duplicate elements. The final answer is then returned.
  • The answer is then displayed in web console using console.log() method.

Example

Here is a complete example code implementing above mentioned steps for writing a javaScript program for counting sets of 1s and 0s in a binary matrix.

let arr = [[1, 0, 1], [0, 1, 0]];
let cols = 3;
let rows = 2;
function fun(arr) {
    let ans = 0;
    for (let i = 0; i 

Conclusion

In this article we understood to write JavaScript program for counting sets of 1s and 0s in a binary matrix. We have discussed with stepwise code explanation. The above code has time complexity of O(n^2).

Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
Updated on: 2025-01-10T10:46:30+05:30

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements