Abhishek kumar
Abhishek kumar

Reputation: 139

Sum of 2-D Array

How to compare sum of each row in 2-D Array?

int arr[3][3];
2 2 3
5 8 9
4 1 2

I want to compare sum of each row with each and every row of this 2-D array, to check if any two row exists having same sum.

Upvotes: 0

Views: 161

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

As suggested in the comments, you should probably look into using std::array or std::vector which makes certain things a lot easier.

Anyway, you could create a std::map with the sum as Key and a std::vector<size_t> as Value to store all the rows with that sum.

#include <cstddef>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <vector>

template<typename T, size_t Y, size_t X>
auto sum_rows(const T (&arr)[Y][X]) {

    // "res" stores the sums mapped to row numbers
    std::map<T, std::vector<size_t>> res;

    // accumulate each row
    for(size_t y = 0; y < Y; ++y) {
        // the result of accumulate is the key in the map
        // the row is pushed back into the vector that is stored for that key
        res[std::accumulate(std::begin(arr[y]), std::end(arr[y]), T{})].push_back(y);
    }

    return res;
}

int main() {
    int arr[3][3]{
        {2, 2, 3},
        {5, 8, 9},
        {4, 1, 2}
    };

    auto res = sum_rows(arr);

    // show the result
    for(const std::pair<int, std::vector<size_t>>& sumrows : res) {
        int sum = sumrows.first;
        const std::vector<size_t>& rows = sumrows.second;

        std::cout << "rows with sum " << sum << " (" << rows.size() << "):";
        for(size_t row : rows) std::cout << ' ' << row;
        std::cout << '\n';
    }
}

Output:

rows with sum 7 (2): 0 2
rows with sum 22 (1): 1

Upvotes: 1

Related Questions