Skip to content

Commit 1e92501

Browse files
committed
A simple question on 2D array
1 parent a5b4c09 commit 1e92501

File tree

2 files changed

+117
-0
lines changed

2 files changed

+117
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
Given a 6x6 2D Array, arr:
2+
3+
1 1 1 0 0 0
4+
0 1 0 0 0 0
5+
1 1 1 0 0 0
6+
0 0 0 0 0 0
7+
0 0 0 0 0 0
8+
0 0 0 0 0 0
9+
An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation:
10+
11+
a b c
12+
d
13+
e f g
14+
15+
There are 16 hourglasses in . An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print the maximum hourglass sum. The array will always be 6x6.
16+
17+
Example
18+
19+
arr =
20+
-9 -9 -9 1 1 1
21+
0 -9 0 4 3 2
22+
-9 -9 -9 1 2 3
23+
0 0 8 6 6 0
24+
0 0 0 -2 0 0
25+
0 0 1 2 4 0
26+
27+
The 16 hourglass sums are:
28+
29+
-63, -34, -9, 12,
30+
-10, 0, 28, 23,
31+
-27, -11, -2, 10,
32+
9, 17, 25, 18
33+
The highest hourglass sum is 28 from the hourglass beginning at row 1, column 2:
34+
35+
0 4 3
36+
1
37+
8 6 6
38+
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.
39+
40+
Function Description:
41+
42+
Complete the function hourglassSum in the editor below.
43+
44+
hourglassSum has the following parameter(s):
45+
46+
int arr[6][6]: an array of integers
47+
Returns
48+
49+
int: the maximum hourglass sum
50+
51+
Input Format
52+
Each of the 6 lines of inputs arr[i] contains 6 space-separated integers arr[i][j].
53+
54+
Constraints
55+
-9 <= arr[i][j] <= 9
56+
0 <= i,j <= 5
57+
58+
Output Format
59+
Print the largest (maximum) hourglass sum found in arr.

Array/Hourglass in Array/Solution.cpp

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
// Complete the hourglassSum function below.
6+
int hourglassSum(vector<vector<int>> arr) {
7+
8+
int sum[16]={0};
9+
int a[36];
10+
static int r=0,x=0;
11+
12+
for(int i=0;i<6;i++){
13+
for(int j=0;j<6;j++,r++){
14+
a[r]=arr[i][j];
15+
}
16+
}
17+
18+
19+
for(int i=0;i<22;i++,x++){
20+
sum[x]=a[i]+a[i+1]+a[i+2]+a[i+7]+a[i+12]+a[i+13]+a[i+14];
21+
if(i==3 || i==9 || i==15)
22+
i+=2;
23+
cout << sum[x] << " ";
24+
}
25+
26+
int large = sum[0];
27+
28+
for(int i=1;i<16;i++){
29+
if(large<sum[i])
30+
large = sum[i];
31+
}
32+
33+
return large;
34+
}
35+
36+
int main()
37+
{
38+
ofstream fout(getenv("OUTPUT_PATH"));
39+
40+
vector<vector<int>> arr(6);
41+
for (int i = 0; i < 6; i++) {
42+
arr[i].resize(6);
43+
44+
for (int j = 0; j < 6; j++) {
45+
cin >> arr[i][j];
46+
}
47+
48+
cin.ignore(numeric_limits<streamsize>::max(), '\n');
49+
}
50+
51+
int result = hourglassSum(arr);
52+
53+
fout << result << "\n";
54+
55+
fout.close();
56+
57+
return 0;
58+
}

0 commit comments

Comments
 (0)