Find the row with the maximum count of unique elements in a given Matrix using C++


Programmers frequently encounter scenarios where they must examine and manage data saved in matrices or multidimensional arrays. A prevalent duty is to identify the row within a matrix that contains the maximum number of unparalleled components, which proves beneficial for tasks involving tabular data sorting, image processing and data analytics. Our article explores how one can use C++ to achieve this goal.

Syntax

In order to avoid ambiguity and confusion, it is advisable that we get acquainted with the syntax applied in our forthcoming code by first examining the chosen method beforehand.

int findRowWithHighestUniqueElements(const std::vector<std::vector<int>>& matrix)

This approach entails taking a matrix in vectorized form consisting of integers and vectors, and identifying the index of the row containing the greatest quantity of unique elements. In the event that numerous rows possess comparable counts, this technique will choose the first encountered instance.

Algorithm

To determine which row within a provided matrix has the most unique elements, we recommend carrying out the following algorithmic procedure −

  • Initialize a variable maxCount to keep track of the maximum count of unique elements found.

  • Initialize a variable rowIndex to store the index of the row with the highest count.

  • Iterate over each row in the matrix −

  • Create a set to store unique elements encountered in the current row.

  • To accurately capture all elements within our dataset we need to check every single entry contained within a given row- one by one. Should an element not currently reside in our established set. It needs to be added at this time..

  • In the event that the set's dimensions surpass maxCount, make certain to adjust maxCount and rowIndex properly

  • Return rowIndex.

Approach 1: Using Sets

The utilization of sets to monitor the exclusive elements contained within individual rows is the strategy carried out in this approach.

Example

#include <iostream>
#include <vector>
#include <set>

int findRowWithHighestUniqueElements(const std::vector<std::vector<int>>& matrix) {
   int maxCount = 0;
   int rowIndex = -1;

   for (int i = 0; i < matrix.size(); ++i) {
      std::set<int> uniqueElements;
      for (int j = 0; j < matrix[i].size(); ++j) {
         uniqueElements.insert(matrix[i][j]);
      }
      if (uniqueElements.size() >= maxCount) {  // Modified condition to include equal count
         maxCount = uniqueElements.size();
         rowIndex = i;
      }
   }
   return rowIndex;
}

int main() {
   std::vector<std::vector<int>> matrix = {{1, 2, 3, 4},
                                          {4, 5, 6, 7},
                                          {1, 2, 3, 8},
                                          {9, 10, 11, 12},
                                          {13, 14, 15, 16}};  // Added an extra row with unique elements

   int rowWithHighestUniqueElements = findRowWithHighestUniqueElements(matrix);
   std::cout << "Row with the highest count of unique elements: " << rowWithHighestUniqueElements << std::endl;

   return 0;
}

Output

Row with the highest count of unique elements: 4

Explanation

Before determining which row of a given matrix contains the highest count of unique elements present therein, two parameters must be initialized − one representing the maximum count thus far (maxCount), and another representing which row holds this position (rowIndex). With these basics in place, we can begin iterating over each row found within our matrix.

Each individual row is subjected to collecting up its distinct values seen so far in an empty set titled 'uniqueElements'. The contents at each index location will then have their uniqueness assessed upon insertion before either being stored or disregarded depending on previous presence. If adding a new input to our increasingly-complete collection then brings its size beyond that of maxCount's existing value at present - necessitating an update - both getMax and rowIndex must have assigned values adjusted accordingly without delay in order not skew final output. Once all necessary rows have been traversed through successfully without any changes as described made past then results are officially ready and can return rowIndex for correct answer output.

Approach 2: Using Maps

An alternate method is to employ maps for recording the number of occurrences of every distinct item within each row. The row possessing the greatest frequency of distinct elements among all rows would be determined by comparing the values saved in the map −

Example

#include <iostream>
#include <vector>
#include <map>

int findRowWithHighestUniqueElements(const std::vector<std::vector<int>>& matrix) {
   int maxCount = 0;
   int rowIndex = -1;

   for (int i = 0; i < matrix.size(); ++i) {
      std::map<int, int> elementCount;
      for (int j = 0; j < matrix[i].size(); ++j) {
         elementCount[matrix[i][j]]++;
      }
      if (elementCount.size() >= maxCount) {  // Modified condition to include equal count
         maxCount = elementCount.size();
         rowIndex = i;
      }
   }

   return rowIndex;
}

int main() {
   std::vector<std::vector<int>> matrix = {{1, 2, 3, 4},
                                          {4, 5, 6, 7},
                                          {1, 2, 3, 8},
                                          {9, 10, 11, 12},
                                          {13, 14, 15, 16}};  // Added an extra row with unique elements

   int rowWithHighestUniqueElements = findRowWithHighestUniqueElements(matrix);
   std::cout << "Row with the highest count of unique elements: " << rowWithHighestUniqueElements << std::endl;

   return 0;
}

Output

Row with the highest count of unique elements: 4

Explanation

Our code aims to determine which specific indexing position corresponds to matrix rows holding unprecedented counts of unique elements. We can achieve this by initiating two key variable trackers − maxCount and rowIndex. This will enable us to keep tabs on the maximum number of unique count instances we’ve encountered so far, along with their respective row position in the matrix. At the onset of each new loop iteration, an empty “elementCount” map gets created to house counts for each unique element occurring within that row. Through per-element inspections within a single row data set, we can iteratively update “elementCount'' values and continue record tabulation dynamically throughout our script logic flow. Whenever our map reaches size counts exceeding current maxCount value limits (a new local record), we adjust values assigned to maxCoun and rowIndex accordingly so that record-keeping remains up-to-date throughout all input processing flows. Ultimately, we complete by returning updated rowIndex as our final output data result.

Conclusion

This article explores two methods for determining the row with the highest number of rare items present within a supplied matrix by utilizing C++ programming language through example codes and explanations elaborated below.

The first strategy focused on spot-checking exclusive items by employing sets while maps were utilized in another method that counted frequencies necessary for all individual item occurrences discovered during our testing phase.

Both procedures delivered favorable results based on our set objectives towards identifying singular rows within matrices; nonetheless, choosing between them largely hinges on what particular needs your development projects require.

By highly understanding the syntax structure in C++, programmers can form unique algorithms and approaches tailored to their project's specifications. The executable code examples demonstrated are an excellent launching point for integrating these ideas into one's applications.

With our various techniques, you can confidently tackle any matrix-related problems that concern working with matrices in C++ by applying our proven strategies while using proper syntax.

Updated on: 25-Jul-2023

41 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements