Posts Day11 - 2D Arrays (Python 3)
Post
Cancel

Day11 - 2D Arrays (Python 3)

  • URL : https://www.hackerrank.com/challenges/30-2d-arrays/problem

  • Objective
    • Today, we’re building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video!
  • 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:
      1
      2
      3
      
        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.
  • Input Format
    • There are 6 lines of input, where each line contains 6 space-separated integers describing 2D Array A; every value in A will be in the inclusive range of -9 to 9.
  • Constraints
    • -9 <= A[i][j] <= 9
    • 0 <= i,j <= 5
  • Output Format
    • Print the largest (maximum) hourglass sum found in A.

문제풀이

  • 6 x 6의 배열에서 모든 3 x 3 배열의 합계 중 가장 큰 수를 출력
  • 배열의 인덱스를 for문으로 주고 각 경우의 수를 다 더하여 리스트에 추가시킨 뒤 가장 큰수를 출력
  • 2번째 행은 2번째 숫자만 더해야함
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import math
import os
import random
import re
import sys

if __name__ == '__main__':
    arr = []
    result = []
    for _ in range(6):
        arr.append(list(map(int, input().rstrip().split())))
    
    for i in range(4):
        for j in range(4):
            result.append(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])
    print(max(result))
1
2
3
4
5
6
arr = [[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]]
1
2
3
4
5
6
7
8
9
# arr[0][0] ~ arr[2][2]
result = []
for i in range(4):
    for j in range(4):
        result.append(arr[i][j] + arr[i][j+1] + arr[i][j+2] + \
                      arr[i+1][j] + arr[i+1][j+1] + arr[i+1][j+2] + \
                      arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2])
print(result)
print(max(result))
1
2
[7, 5, 2, 0, 6, 9, 11, 8, 5, 10, 13, 10, 3, 11, 19, 16]
19
This post is licensed under CC BY 4.0 by the author.