Related Articles
Compress a matrix into a single number using given operations
• Last Updated : 26 Feb, 2021

Given a matrix mat[][] of dimension M * N, the task is to first compress it to obtain an array and, then compress it again to obtain a single integer using following operations:

• When a matrix is compressed, its value’s binary representation gets compressed.
• Therefore, each bit is considered, and if a position of a bit has S set bits and NS non-set bits, then the bit is set for the position if S > NS and unset otherwise.
• Each column is compressed to turn the matrix into an array, then that array is compressed further into a single number.

For example, if 5, 2, 3, and 1 gets compressed then their binary representations (101)2, (010)2, (011)2, and (001)2 gets compressed then for the 0th and 1st positions, S ≤ NS and for the 2nd position S > NS, then the number modifies to (001)2 = 1.

Examples:

Input: arr[][] ={{ 3, 2, 4}, {5, 6, 1}, {8, 1, 3}}
Output: 1
Explanation: The array obtained after compressing the given matrix from top is {1, 2, 1 }.Then, the obtained array is compressed to 1.

Input: arr[][] = {{ 5, 3}, {6, 7}}
Output: 0

Approach: The idea is to count the number of set bits for each position. Follow the steps below to solve the problem:

• Traverse through each element of each column of a matrix and compress each column to a single number.
• Count the number of set bits for each position.
• Set the bit for the positions with number of set bits exceeding the number of unset bits.
• Calculate the value after deciding whether to set or not to set the bit for each position.
• After obtaining an array, apply the same steps to obtain the required integer.

Below is the implementation of the above approach:

## C++

 `// c++ Program for the above approach``#include``using` `namespace` `std;` `  ``// Function to compress an``  ``// array to a single number``  ``vector<``int``> append(vector<``int``> arr, ``int` `x)``  ``{``    ` `    ``// create a new ArrayList``    ``arr.push_back(x);``    ``return` `arr;``  ``}``  ` `  ``int` `compress(vector<``int``> arr)``  ``{` `    ``// Stores the required integer``    ``int` `ans = 0;``    ``int` `getBit = 1;` `    ``// Checking for each position``    ``for` `(``int` `i = 0; i < 32; i++)``    ``{``      ``int` `S = 0;``      ``int` `NS = 0;``      ``for` `(``int` `j = 0; j < arr.size(); j++)``      ``{` `        ``// Count set and unset bit``        ``int` `temp = getBit & arr[j];``        ``if` `(temp == 1) {``          ``S += 1;``        ``}``        ``else` `{``          ``NS += 1;``        ``}` `        ``// If count of set bits exceeds``        ``// count of unset bits``        ``if` `(S > NS) {` `          ``// Add value of set bits to ans``          ``ans += ``pow``(2, i);``        ``}``        ``getBit <<= 1;``      ``}``    ``}` `    ``return` `ans;``  ``}` `  ``// Function to compress``  ``// matrix to a single number`` ``int` `getResult(vector> mat)``  ``{` `    ``// Stores compressed array``    ``vector<``int``> compressedArr;``    ``int` `len = mat.size();``    ``int` `len2 = mat.size();``    ``for` `(``int` `i = 0; i < len; i++)``    ``{``      ``vector<``int``> col;` `      ``for` `(``int` `j = 0; j < len2; j++)``      ``{``        ``col = append(col, mat[j][i]);``      ``}``      ` `      ``// Compress all columns``      ``// to a single number``      ``compressedArr = append(compressedArr, compress(col));``    ``}``    ``return` `compress(compressedArr);``  ``}` `  ``// Driver Code``  ``int` `main()``  ``{``    ``vector> mat{{3, 2, 4 },{5, 6, 1},{8, 1, 3}};``    ``cout<<(getResult(mat));``  ``}` `// THIS CODE IS CONTRIBUTED BY SURENDRA_GANGWAR.`

## Java

 `// Java Program for the above approach``import` `java.io.*;``import` `java.lang.*;``import` `java.lang.Math;``import` `java.util.*;``class` `GFG {` `  ``// Function to compress an``  ``// array to a single number``  ``static` `Integer[] append(Integer arr[], ``int` `x)``  ``{``    ``// create a new ArrayList``    ``List arrlist``      ``= ``new` `ArrayList(Arrays.asList(arr));` `    ``// Add the new element``    ``arrlist.add(x);` `    ``// Convert the Arraylist to array``    ``arr = arrlist.toArray(arr);` `    ``// return the array``    ``return` `arr;``  ``}``  ``static` `int` `compress(Integer[] arr)``  ``{` `    ``// Stores the required integer``    ``int` `ans = ``0``;``    ``int` `getBit = ``1``;` `    ``// Checking for each position``    ``for` `(``int` `i = ``0``; i < ``32``; i++) {` `      ``int` `S = ``0``;``      ``int` `NS = ``0``;` `      ``for` `(``int` `j = ``0``; j < arr.length; j++) {` `        ``// Count set and unset bit``        ``int` `and = getBit & arr[j];``        ``if` `(and == ``1``) {``          ``S += ``1``;``        ``}``        ``else` `{``          ``NS += ``1``;``        ``}` `        ``// If count of set bits exceeds``        ``// count of unset bits``        ``if` `(S > NS) {` `          ``// Add value of set bits to ans``          ``ans += Math.pow(``2``, i);``        ``}``        ``getBit <<= ``1``;``      ``}``    ``}` `    ``return` `ans;``  ``}` `  ``// Function to compress``  ``// matrix to a single number``  ``static` `int` `getResult(Integer[][] mat)``  ``{` `    ``// Stores compressed array``    ``Integer[] compressedArr = {};``    ``int` `len = mat.length;``    ``int` `len2 = mat[``0``].length;``    ``for` `(``int` `i = ``0``; i < len; i++)``    ``{``      ``Integer[] col = {};` `      ``for` `(``int` `j = ``0``; j < len2; j++)``      ``{``        ``col = append(col, mat[j][i]);``      ``}``      ` `      ``// Compress all columns``      ``// to a single number``      ``compressedArr``        ``= append(compressedArr, compress(col));``    ``}``    ``return` `compress(compressedArr);``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``Integer[][] mat = { { ``3``, ``2``, ``4` `},``                       ``{ ``5``, ``6``, ``1` `},``                       ``{ ``8``, ``1``, ``3` `} };``    ``System.out.println(getResult(mat));``  ``}``}` `// This code is contibuted by rohitsingh07052.`

## Python3

 `# Python Program for the above approach` `# Function to compress an``# array to a single number``def` `compress(arr):` `  ``# Stores the required integer``  ``ans ``=` `0``  ``getBit ``=` `1` `  ``# Checking for each position``  ``for` `i ``in` `range``(``32``):` `    ``S ``=` `0``    ``NS ``=` `0` `    ``for` `j ``in` `arr:` `      ``# Count set and unset bits``      ``if` `getBit&j:``        ``S ``+``=` `1``      ``else``:``        ``NS ``+``=` `1` `    ``# If count of set bits exceeds``    ``# count of unset bits``    ``if` `S > NS:`` ` `      ``# Add value of set bits to ans``      ``ans ``+``=` `2``*``*``i``    ``getBit <<``=` `1` `  ``return` `ans` `# Function to compress``# matrix to a single number``def` `getResult(mat):` `  ``# Stores compressed array``  ``compressedArr ``=` `[]` `  ``for` `i ``in` `range``(``len``(mat)):``    ``col ``=` `[]``    ``for` `j ``in` `range``(``len``(mat[``0``])):``      ``col.append(mat[j][i])` `    ``# Compress all columns``    ``# to a single number ``    ``compressedArr.append(compress(col))` `  ``return` `compress(compressedArr)` `# Driver Code``mat ``=` `[ [ ``3``, ``2``, ``4``], [``5``, ``6``, ``1``], [``8``, ``1``, ``3``] ]` `print``( getResult(mat) )`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Function to compress an``// array to a single number``static` `int``[] append(``int` `[]arr, ``int` `x)``{``    ` `    ``// create a new List``    ``List<``int``> arrlist = ``new` `List<``int``>(arr);``    ` `    ``// Add the new element``    ``arrlist.Add(x);``    ` `    ``// Convert the Arraylist to array``    ``arr = arrlist.ToArray();``    ` `    ``// return the array``    ``return` `arr;``}` `static` `int` `compress(``int``[] arr)``{` `    ``// Stores the required integer``    ``int` `ans = 0;``    ``int` `getBit = 1;``    ` `    ``// Checking for each position``    ``for``(``int` `i = 0; i < 32; i++)``    ``{``    ` `        ``int` `S = 0;``        ``int` `NS = 0;``        ` `        ``for``(``int` `j = 0; j < arr.Length; j++)``        ``{` `            ``// Count set and unset bit``            ``int` `and = getBit & arr[j];``            ``if` `(and == 1)``            ``{``                ``S += 1;``            ``}``            ``else``            ``{``                ``NS += 1;``            ``}``            ` `            ``// If count of set bits exceeds``            ``// count of unset bits``            ``if` `(S > NS)``            ``{``                ` `                ``// Add value of set bits to ans``                ``ans += (``int``)Math.Pow(2, i);``            ``}``            ``getBit <<= 1;``        ``}``    ``}``    ` `    ``return` `ans;``}` `// Function to compress``// matrix to a single number``static` `int` `getResult(``int``[,] mat)``{``    ` `    ``// Stores compressed array``    ``int``[] compressedArr = {};``    ``int` `len = mat.GetLength(0);``    ``int` `len2 = mat.GetLength(1);``    ` `    ``for``(``int` `i = 0; i < len; i++)``    ``{``        ``int``[] col = {};``        ` `        ``for` `(``int` `j = 0; j < len2; j++)``        ``{``            ``col = append(col, mat[j,i]);``        ``}``        ` `        ``// Compress all columns``        ``// to a single number``        ``compressedArr = append(compressedArr,``                               ``compress(col));``    ``}``    ``return` `compress(compressedArr);``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ``int``[,] mat = { { 3, 2, 4 },``                   ``{ 5, 6, 1 },``                   ``{ 8, 1, 3 } };``                   ` `    ``Console.WriteLine(getResult(mat));``}``}` `// This code is contributed by shikhasingrajput`
Output:
`1`

Time Complexity: O(N*M)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up