새소식

인기 검색어

알고리즘/알고리즘 문제풀이

[HackerRank] 2d array

  • -

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

 

2D Array - DS | HackerRank

How to access and use 2d-arrays.

www.hackerrank.com

 

#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);

/*
 * Complete the 'hourglassSum' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts 2D_INTEGER_ARRAY arr as parameter.
 */

int hourglassSum(vector<vector<int>> arr) {
    // find ourglass sums 4*4 2d array
    // 00 01 02 11 20 21 22
    // ij
    // (i,j) (i,j+1), (i,j+2), 
    // (j+1, j+1)
    // (i+2, j), (i+2, j+1), (i+2, j+2)
    // i,j  0~3
    vector<vector<int>> hourglassSums(16, vector<int>(4, 0));
    int sum;
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            sum = arr[i][j] + arr[i][j+1] + arr[i][j+2] +
                    arr[i+1][j+1] +
                    arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2];
            hourglassSums[i][j] = sum;
        }
    }
    // find biggest number from 4*4 2d array 
    int max = -9999;
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            if (max < hourglassSums[i][j])
            {
                max = hourglassSums[i][j];
            }

        }
    }
    return max;
}

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

    vector<vector<int>> arr(6);

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

        string arr_row_temp_temp;
        getline(cin, arr_row_temp_temp);

        vector<string> arr_row_temp = split(rtrim(arr_row_temp_temp));

        for (int j = 0; j < 6; j++) {
            int arr_row_item = stoi(arr_row_temp[j]);

            arr[i][j] = arr_row_item;
        }
    }

    int result = hourglassSum(arr);

    fout << result << "\n";

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}

vector<string> split(const string &str) {
    vector<string> tokens;

    string::size_type start = 0;
    string::size_type end = 0;

    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));

        start = end + 1;
    }

    tokens.push_back(str.substr(start));

    return tokens;
}

'알고리즘 > 알고리즘 문제풀이' 카테고리의 다른 글

[HackerRank] Time Conversion  (0) 2023.10.19
[HackerRank] Mini-Max-Sum  (0) 2023.10.19
[HackerRank] Plus Minus  (0) 2023.10.19
[HackerRank] arrays-ds  (0) 2023.10.19
[HackerRank] Dynamic Array  (0) 2023.10.19
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.