2 Dim Arrays

Hi there,

I have a 2-dim array, and I want to check how many rows have the same value for a specific column.

For example:

Mod1 Mod2 Mod3 Mod4 Mod5
ID1 5 12 88 66 67
ID2 8 14 78 44 45
ID3 7 12 54 38 39
ID4 4 11 36 87 34
ID5 3 12 25 22 18

The program should find that ID1, ID3 and ID5 have the same value in Mod2.

Any help please?

Thanks and regards
Last edited on
its going to take a little work.

one way to do it is to extract the column in question into a 1-d array, sort it, and check adjacent values. This gives you the value and # of instances, but not the original row (if you need the row, youll want to have ID or ROWNUM tag along in the sort to pull it back out, don't sort on it, just have it ride along in the data). This would be a complex NlogN answer. It may be the best for general purpose data.

the brute force way would be to get a row's value and check it against every other row in a n*n double loop.

if you know the data is of type int and has a max value of N, you can use a bucket sort approach to solve it in ~O(n).

If the matrix is a small fixed size, you can do other simple solutions that exploit that.



Read the 2D array by column into a std::map <int, int> where the key is the col member and the value is the frequency of its occurrence:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>
#include <map>

auto constexpr SIZE = 5;

int main()
{
    int arr[SIZE][SIZE] = {{5, 12, 88, 66, 67}, {8, 14, 78, 44, 45},{7, 12, 54, 38, 39},{4, 11, 36, 87, 34},{3, 12, 25, 22, 18}};

    std::vector<std::map<int, int>> myVec{};

    for (size_t j = 0; j < SIZE; ++j)
    {
        std::map<int, int> tempMap{};
        for (size_t i = 0; i < SIZE; ++i)
        {
            tempMap[arr[i][j]]++;
        }
        myVec.push_back(tempMap);
    }
    for (const auto& elemVec : myVec)
    {
        for (const auto& elemMap : elemVec)
        {
            std::cout << elemMap.first << " " << elemMap.second << "\n";
        }
        std::cout << "\n";
    }
}

Topic archived. No new replies allowed.