Home > Software engineering >  get frequency elements from 2D vector?
get frequency elements from 2D vector?

Time:04-11

i try to get frequency elements for 2D vector for example : my vector vector<vector> edge { {4, 2, 3}, {4, 5, 6}, {2, 8, 9} }; result: 4 and 2 because appears 2 time in the 2D vector i'm not familiar with c . my code return only one element "the first frequent element but i need to return evry frequency elemnt in the 2d vector .

#include <iostream>
#include <vector>
#include <map>
#include <iomanip>
using namespace std;
int main()
{
   
   vector<vector<int>> edge
   {
       {4, 2, 3},
       {4, 5, 6},
       {2, 8, 9}
   };
    map<int, unsigned int> occurrences;
            // Process the hypergraph.
            for (int i = 0; i < edge.size(); i  )
            {
              for (int j = 0; j < edge[i].size(); j  )
              {
                 occurrences[edge[i][j]]  ;
              }
            }
            unsigned currentMax = 0;
            unsigned arg_max = 0;
            // Show the results:
            for (map<int, unsigned int>::iterator it = occurrences.begin(); it != occurrences.end();   it)
            {
               if (it ->second > currentMax) {
                   arg_max = it->first;
                    currentMax = it->second;
               }
            }
            cout << "Value " << arg_max << " occurs " << currentMax << " times " << endl;
   return 0;
}

CodePudding user response:

In your first set of for-loops where you iterate over edge, you could identify the max_count value, subsequently, you could use that value to selectively print when iterating over your map:

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

int main() {
  std::vector<std::vector<int>> edge
  {
    {4, 2, 3},
    {4, 5, 6},
    {2, 8, 9}
  };
  unsigned int max_count = 0;
  std::map<int, unsigned int> counts;
  for (const std::vector<int> &row : edge) {
    for (const int &ele : row) {
      if (  counts[ele] > max_count) {
        max_count = counts.at(ele);
      }
    }
  }
  for (const auto& [val, count] : counts) {
    if (count == max_count) {
      std::cout << "Value " << val << " occurs " << count << " times\n";
    }
  }
  return 0;
}

Output:

Value 2 occurs 2 times
Value 4 occurs 2 times

CodePudding user response:

my code return only one element "the first frequent element but i need to return evry frequency elemnt in the 2d vector .

Every frequency element is in your occurences variable. Instead of only keeping the arg_max you can print the occurence of each value.

Also note that, because you used a map over an unordered_map you already have the results nicely sorted when you print them.

  •  Tags:  
  • c
  • Related