Day 11.2 solution.

This commit is contained in:
Anna Rose 2018-12-12 16:46:57 -05:00
parent a409571bd8
commit 2d71871cf4
No known key found for this signature in database
GPG Key ID: 8D9ACA841015C59A
4 changed files with 77 additions and 4 deletions

17
2018/day11-2.go Normal file
View File

@ -0,0 +1,17 @@
package main
import (
"fmt"
"internal/day11"
"internal/util"
)
func main() {
serialNumber := util.ReadInputInts()[0]
grid := day11.GenerateGrid(serialNumber)
x, y, n := day11.FindBestWindow(grid)
fmt.Printf("%d,%d,%d\n", x, y, n)
}

View File

@ -13,9 +13,9 @@ func DebugPrintGrid(grid [][]int) {
}
}
func DebugPrint5x5(grid [][]int, x, y int) {
for i := y - 1; i < y+4; i++ {
for j := x - 1; j < x+4; j++ {
func DebugPrintNxN(grid [][]int, x, y, n int) {
for i := y; i < y+n; i++ {
for j := x; j < x+n; j++ {
fmt.Printf("%3d", grid[i][j])
}
fmt.Println()

View File

@ -1,5 +1,9 @@
package day11
import (
"internal/util"
)
const GridSize = 300
func GenerateGrid(serialNumber int) [][]int {
@ -62,3 +66,48 @@ func sumNxN(grid [][]int, x, y, n int) int {
return total
}
func FindBestWindow(grid [][]int) (int, int, int) {
largest := grid[0][0]
bestX := 0
bestY := 0
bestN := 1
for x := 0; x < GridSize; x++ {
for y := 0; y < GridSize; y++ {
sum, n := findBestSquare(grid, x, y)
if sum > largest {
largest = sum
bestX = x
bestY = y
bestN = n
}
}
}
return bestX + 1, bestY + 1, bestN
}
func findBestSquare(grid [][]int, x, y int) (int, int) {
sum := grid[y][x]
bestSum := sum
bestN := 1
for n := 2; n < util.Min(GridSize-y, GridSize-x); n++ {
for i := y; i < y+n; i++ {
sum += grid[i][x+n-1]
}
for i := x; i < x+n-1; i++ {
sum += grid[y+n-1][i]
}
if sum > bestSum {
bestSum = sum
bestN = n
}
}
return bestSum, bestN
}

View File

@ -1,8 +1,15 @@
package util
func abs(x int) int {
func Abs(x int) int {
if x < 0 {
return -x
}
return x
}
func Min(i, j int) int {
if i < j {
return i
}
return j
}