Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created September 8, 2016 10:40
Show Gist options
  • Save nichtemna/2dbe6d4ef84bae3406486313d4dc1ed2 to your computer and use it in GitHub Desktop.
Save nichtemna/2dbe6d4ef84bae3406486313d4dc1ed2 to your computer and use it in GitHub Desktop.
2D Array - DS
/**
Given a 2D Array, :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation:
a b c
d
e f g
There are hourglasses in , and an hourglass sum is the sum of an hourglass' values.
Task
Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.
Input Format
There are lines of input, where each line contains space-separated integers describing 2D Array ; every value in will be in the inclusive range of to .
Constraints
Output Format
Print the largest (maximum) hourglass sum found in .
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19
*/
public class Hourglass {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for (int arr_i = 0; arr_i < 6; arr_i++) {
for (int arr_j = 0; arr_j < 6; arr_j++) {
arr[arr_i][arr_j] = in.nextInt();
}
}
System.out.print(getMax(arr));
}
private static int getMax(int[][] arr) {
int max = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int local_max = 0;
local_max += arr[i][j];
local_max += arr[i + 1][j];
local_max += arr[i + 2][j];
local_max += arr[i + 1][j + 1];
local_max += arr[i][j + 2];
local_max += arr[i + 1][j + 2];
local_max += arr[i + 2][j + 2];
if (local_max > max) {
max = local_max;
}
}
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment