Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

30 days of code in Go: Day 11 - 2D Arrays

Hi there! The challenge of today confused me a little in their definition, but they had a good example so it was not hard to get it. Basically I had to read a $6 \times 6$ matrix and iterate over it summing a pattern of elements like

abc
 d
efg

that is called an hourglass. So, I just had to iterate through an array and sum 7 elements of it for each iteration. My solution is below.

package main

import "fmt"

func getMaxHourGlass(A [6][6]int) int {
  var maxSum int = -99999
  for i := 1; i < 5; i++ {
    for j := 1; j < 5; j++ {
      sum := A[i][j]
      sum = sum + A[i+1][j+1] + A[i+1][j] + A[i+1][j-1]
      sum = sum + A[i-1][j+1] + A[i-1][j] + A[i-1][j-1]
      if sum > maxSum {
        maxSum = sum
      }
    }
  }

  return maxSum
}

func main() {

  var A [6][6]int
  // read matrix
  for i := 0; i < 6; i++ {
    for j := 0; j < 6; j++ {
      fmt.Scanf("%d", &A[i][j])
    }
  }
  fmt.Printf("%d\n", getMaxHourGlass(A))

}

To build and run it:

$ go build day_11.go
$ ./day_11
# 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
# output
19

As you may have noticed, the program reads a matrix from standard input and then outputs a single number with the sum of the maximum hourglass.

That’s all for this post! Thanks for reading!

Tags
comments powered by Disqus