Skip to content

Instantly share code, notes, and snippets.

@namthatman
Created April 13, 2019 08:22
Show Gist options
  • Save namthatman/3e5a3eb6989b1c52ddc2eb0d1d9043fc to your computer and use it in GitHub Desktop.
Save namthatman/3e5a3eb6989b1c52ddc2eb0d1d9043fc to your computer and use it in GitHub Desktop.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the hourglassSum function below.
def hourglassSum(arr):
if arr is None:
return 0
newrow = len(arr)-2
newcol = len(arr[0])-2
if newrow <= 0 or newcol <= 0:
return 0
hourglass = [[0 for col in range(newcol)] for row in range(newrow)]
for row in range(len(hourglass)):
for col in range(len(hourglass[0])):
hourglass[row][col] = arr[row][col] + arr[row][col+1] + arr[row][col+2]
hourglass[row][col] += arr[row+1][col+1]
hourglass[row][col] += arr[row+2][col] + arr[row+2][col+1] + arr[row+2][col+2]
maxValue = max(hourglass[0])
for row in range(1,len(hourglass)):
if maxValue < max(hourglass[row]):
maxValue = max(hourglass[row])
return maxValue
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
result = hourglassSum(arr)
fptr.write(str(result) + '\n')
fptr.close()
Given a 6x6 2D Array, arr:
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 arr's graphical representation:
a b c
d
e f g
There are 16 hourglasses in arr, and 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.
For example, given the 2D array:
-9 -9 -9 1 1 1
0 -9 0 4 3 2
-9 -9 -9 1 2 3
0 0 8 6 6 0
0 0 0 -2 0 0
0 0 1 2 4 0
We calculate the following 16 hourglass values:
-63, -34, -9, 12,
-10, 0, 28, 23,
-27, -11, -2, 10,
9, 17, 25, 18
Our highest hourglass value is 28 from the hourglass:
0 4 3
1
8 6 6
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.
Function Description
Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.
hourglassSum has the following parameter(s):
arr: an array of integers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment