Solution for 11.1

This commit is contained in:
Anna Rose 2018-12-12 16:14:57 -05:00
parent bd7cc5ce68
commit a409571bd8
No known key found for this signature in database
GPG Key ID: 8D9ACA841015C59A
3 changed files with 104 additions and 0 deletions

17
2018/day11-1.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 := day11.FindBestWindow3x3(grid)
fmt.Printf("%d,%d\n", x, y)
}

View File

@ -0,0 +1,23 @@
package day11
import (
"fmt"
)
func DebugPrintGrid(grid [][]int) {
for y := 0; y < GridSize; y++ {
for x := 0; x < GridSize; x++ {
fmt.Printf("%3d", grid[y][x])
}
fmt.Println()
}
}
func DebugPrint5x5(grid [][]int, x, y int) {
for i := y - 1; i < y+4; i++ {
for j := x - 1; j < x+4; j++ {
fmt.Printf("%3d", grid[i][j])
}
fmt.Println()
}
}

View File

@ -0,0 +1,64 @@
package day11
const GridSize = 300
func GenerateGrid(serialNumber int) [][]int {
grid := make([][]int, GridSize)
for i := 0; i < GridSize; i++ {
grid[i] = make([]int, GridSize)
}
// Calculate the power level in each fuel cell
for y := 0; y < GridSize; y++ {
for x := 0; x < GridSize; x++ {
// Find the fuel cell's rack ID, which is its X coordinate plus 10.
rackID := (x + 1) + 10
// Begin with a power level of the rack ID times the Y coordinate.
// Increase the power level by the value of the grid serial number (your puzzle input).
// Set the power level to itself multiplied by the rack ID.
power := ((rackID * (y + 1)) + serialNumber) * rackID
// Keep only the hundreds digit of the power level (so 12345 becomes 3; numbers with no hundreds digit become 0).
power = (power % 1000) / 100
// Subtract 5 from the power level.
power -= 5
grid[y][x] = power
}
}
return grid
}
func FindBestWindow3x3(grid [][]int) (int, int) {
largest := sumNxN(grid, 0, 0, 3)
bestX := 0
bestY := 0
for x := 1; x < GridSize-2; x++ {
for y := 1; y < GridSize-2; y++ {
sum := sumNxN(grid, x, y, 3)
if sum > largest {
largest = sum
bestX = x
bestY = y
}
}
}
return bestX + 1, bestY + 1
}
func sumNxN(grid [][]int, x, y, n int) int {
total := 0
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
total += grid[y+i][x+j]
}
}
return total
}