Latest news:
Sahih al-Bukhari (সহীহ বুখারী) is a free Hadith application for android. This application is advertisement free. Download now https://play.google.com/store/apps/details?id=com.akramhossin.bukharisharif
Objective
Today, we are building on our knowledge of arrays by adding another dimension.
Context
Given a 6 x 6 2D Array, A:
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 A to be a subset of values with indices falling in this pattern in A‘s graphical representation:
a b c d e f g
There are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass’ values.
Task
Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.
Example
In the array shown above, the maximum hourglass sum is 7 for the hourglass in the top left corner.
Input Format
There are 6 lines of input, where each line contains 6 space-separated integers that describe the 2D Array A.
Constraints
-9 ≤ A[i][j] ≤ 9
0 ≤ i, j ≤ 5
Output Format
Print the maximum hourglass sum in A.
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
Explanation
A contains the following hourglasses:
1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 2 0 2 4 2 4 4 4 4 0 1 1 1 1 1 0 1 0 0 0 0 0 0 2 4 4 0 0 0 0 0 2 0 2 0 2 0 0 0 0 2 0 2 4 2 4 4 4 4 0 0 0 2 0 0 0 1 0 1 2 1 2 4 2 4 0
The hourglass with the maximum sum (19) is:
2 4 4 2 1 2 4
Solution – Day 11: 2D Arrays
PHP Solution:
$stdin = fopen("php://stdin", "r"); $arr == array(); for ($i = 0; $i < 6; $i++) { fscanf($stdin, "%[^\n]", $arr_temp); $arr[] = array_map('intval', preg_split('/ /', $arr_temp, -1, PREG_SPLIT_NO_EMPTY)); } $next = 1; $nextNext = 2; $valuesArray = []; for ($i = 0; $i <= 3; $i++) { $start = 0; $end = 2; for ($k = $start; $k < $end; $k++) { $hourglasses[$i] = []; for ($n = $start; $n <= $end; $n++) { $hourglasses[$i][0][] = $arr[$i][$n]; $hourglasses[$i][1][] = $arr[$next][$n]; $hourglasses[$i][2][] = $arr[$nextNext][$n]; } if ($end == 5) { $end = 0; } else { $start++; $end++; } $perHourGlassVal = 0; for ($h = 0; $h < 3; $h++) { if ($h != 1) { $hg = $hourglasses[$i][$h]; for ($g = 0; $g < 3; $g++) { $val = $hg[$g]; $perHourGlassVal += $val; } } else { $hg = $hourglasses[$i][$h]; $val = $hg[1]; $perHourGlassVal += $val; } } $valuesArray[] = $perHourGlassVal; } $next++; $nextNext++; } print max($valuesArray); fclose($stdin);
Views : 430