Elnee
7/28/2019 - 12:43 PM

2D-array-hourglasses-sum.cxx

// LINK TO EXERCISE: https://www.hackerrank.com/challenges/2d-array/problem

#include <bits/stdc++.h>

using namespace std;

// Complete the hourglassSum function below.
int hourglassSum(vector<vector<int>> arr) {
    if (arr.size() < 3 || arr[0].size() < 3) return 0;

    int maxHourglassSum = numeric_limits<int>::min();
    int iterationsRight = arr[0].size() - 2;
    int iterationsDown = arr.size() - 2;

    vector<pair<int, int>> indexes {{0, 0}, {0, 1}, {0, 2},
                                            {1, 1},
                                    {2, 0}, {2, 1}, {2, 2}};

    auto movePatternRight = [](pair<int, int>& p) {
        get<1>(p) += 1;
    };

    auto movePatternDownAndLeft = [](pair<int, int>& p) {
        get<1>(p) -= 3;
        get<0>(p) += 1;
    };

    for (int i = 0; i < iterationsDown; ++i) {
        for (int j = 0; j < iterationsRight; ++j) {
            // Calculating sum of hourglasses
            int sum = accumulate(indexes.cbegin(), indexes.cend(), 0, 
                [&arr](int res, pair<int, int> p){
                    return move(res) + arr[get<0>(p)][get<1>(p)];
                });

            if (maxHourglassSum < sum) maxHourglassSum = sum;
            if (j == iterationsRight - 1) break; // Don't move last time

            for_each(indexes.begin(), indexes.end(), movePatternRight);
        }
        for_each(indexes.begin(), indexes.end(), movePatternDownAndLeft);
    }

    return maxHourglassSum;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    vector<vector<int>> arr(6);
    for (int i = 0; i < 6; i++) {
        arr[i].resize(6);

        for (int j = 0; j < 6; j++) {
            cin >> arr[i][j];
        }

        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    int result = hourglassSum(arr);

    fout << result << "\n";

    fout.close();

    return 0;
}