diff --git a/2018/day11-2.go b/2018/day11-2.go new file mode 100644 index 0000000..329381b --- /dev/null +++ b/2018/day11-2.go @@ -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) +} diff --git a/2018/internal/day11/debug.go b/2018/internal/day11/debug.go index 8765eb0..70da914 100644 --- a/2018/internal/day11/debug.go +++ b/2018/internal/day11/debug.go @@ -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() diff --git a/2018/internal/day11/power.go b/2018/internal/day11/power.go index 2bef947..32d0d7b 100644 --- a/2018/internal/day11/power.go +++ b/2018/internal/day11/power.go @@ -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 +} diff --git a/2018/internal/util/math.go b/2018/internal/util/math.go index a3bf4bc..9e1d464 100644 --- a/2018/internal/util/math.go +++ b/2018/internal/util/math.go @@ -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 +}