advent_of_code_2024/day_14/solution.go

141 lines
2.5 KiB
Go
Raw Normal View History

2024-12-14 11:53:29 +00:00
package day_14
import (
"fmt"
"strings"
)
type Robot struct {
pX, pY int
vX, vY int
}
// task:https://adventofcode.com/2024/day/14
func SolveBasic(input string) int {
return solveBasic(input, 101, 103)
}
// task:https://adventofcode.com/2024/day/14
func SolveBasicSmall(input string) int {
return solveBasic(input, 11, 7)
}
func solveBasic(input string, width int, height int) int {
robots := loadRobots(input)
quads := []int{0, 0, 0, 0, 0}
for _, r := range robots {
r.pX = (r.pX + 100*r.vX) % width
r.pY = (r.pY + 100*r.vY) % height
if r.pX < 0 {
r.pX += width
}
if r.pY < 0 {
r.pY += height
}
quad := determineQuad(r, width, height)
quads[quad]++
}
return quads[0] * quads[1] * quads[2] * quads[3]
}
func determineQuad(r Robot, width int, height int) int {
if r.pX < width/2 && r.pY < height/2 {
return 0
}
if r.pX > width/2 && r.pY < height/2 {
return 1
}
if r.pX < width/2 && r.pY > height/2 {
return 2
}
if r.pX > width/2 && r.pY > height/2 {
return 3
}
return 4
}
func loadRobots(input string) []Robot {
var robots []Robot
for _, line := range strings.Split(input, "\n") {
r := Robot{}
_, err := fmt.Sscanf(line, "p=%d,%d v=%d,%d", &r.pX, &r.pY, &r.vX, &r.vY)
if err != nil {
panic(err)
}
robots = append(robots, r)
}
return robots
}
// task:https://adventofcode.com/2024/day/12#part2
func SolveComplex(input string) int {
robots := loadRobots(input)
for i := 0; i < 100000; i++ {
if hasLine(robots) {
printRobots(i, robots)
}
step(robots)
}
return 0
}
func hasLine(robots []Robot) bool {
rows := map[int]int{}
cols := map[int]int{}
for _, r := range robots {
rows[r.pX]++
cols[r.pY]++
}
has10Row := 0
has10Col := 0
for _, v := range rows {
if v >= 15 {
has10Row++
}
}
for _, v := range cols {
if v >= 15 {
has10Col++
}
}
return has10Col >= 2 && has10Row >= 2
}
func step(robots []Robot) {
for i, r := range robots {
r.pX = (r.pX + r.vX) % 101
r.pY = (r.pY + r.vY) % 103
if r.pX < 0 {
r.pX += 101
}
if r.pY < 0 {
r.pY += 103
}
robots[i].pX = r.pX
robots[i].pY = r.pY
}
}
func printRobots(day int, robots []Robot) {
field := createField()
for _, r := range robots {
field[r.pY][r.pX] = '#'
}
fmt.Printf("\n----\nDay: %d\n----\n", day)
for _, line := range field {
fmt.Printf("%s\n", string(line))
}
}
func createField() [][]rune {
field := [][]rune{}
for i := 0; i < 103; i++ {
line := make([]rune, 101)
for j := range line {
line[j] = '.'
}
field = append(field, line)
}
return field
}