Skip to content

Commit

Permalink
day14p2
Browse files Browse the repository at this point in the history
  • Loading branch information
gamersi committed Dec 14, 2024
1 parent 737e80d commit 5e89d61
Show file tree
Hide file tree
Showing 2 changed files with 145 additions and 0 deletions.
101 changes: 101 additions & 0 deletions day14p2/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package day14p2

import (
"io"
"math"

"aoc/utils"
)

type Bot struct {
X, Y int
VX, VY int
}

func Solve(r io.Reader) any {
lines := utils.ReadLines(r)
isTest := len(lines) == 12
if isTest {
return 0 // no test input for this one
}
boardWidth := 101
boardHeight := 103

bots := make([]Bot, len(lines))

for i, line := range lines {
ints := utils.GetInts(line)
px, py, vx, vy := ints[0], ints[1], ints[2], ints[3]
bots[i] = Bot{px, py, vx, vy}
}

MAX_MOVES := 10000

minDoubleOccurences := math.MaxInt
minStep := 0

for step := 1; step <= MAX_MOVES; step++ {
for i, bot := range bots {
bots[i].X += bot.VX
bots[i].Y += bot.VY
if bots[i].X < 0 {
bots[i].X += boardWidth
} else if bots[i].X >= boardWidth {
bots[i].X -= boardWidth
}
if bots[i].Y < 0 {
bots[i].Y += boardHeight
} else if bots[i].Y >= boardHeight {
bots[i].Y -= boardHeight
}
}
do := countDoubleOccurences(bots)
if do < minDoubleOccurences {
minDoubleOccurences = do
minStep = step
}
if minDoubleOccurences <= 1 {
break
}
}

return minStep
}

func countDoubleOccurences(bots []Bot) int {
occurences := make(map[utils.Point]int)

for _, bot := range bots {
occurences[utils.Point{X: bot.X, Y: bot.Y}]++
}

doubleOccurences := 0
for _, count := range occurences {
if count > 1 {
doubleOccurences++
}
}

return doubleOccurences
}

func printBoard(bots []Bot, boardWidth, boardHeight int) {
board := make([][]rune, boardHeight)
for i := range board {
board[i] = make([]rune, boardWidth)
for j := range board[i] {
board[i][j] = '.'
}
}

for _, bot := range bots {
board[bot.Y][bot.X] = '#'
}

for _, row := range board {
for _, r := range row {
print(string(r))
}
println()
}
}
44 changes: 44 additions & 0 deletions day14p2/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package day14p2

import (
"strings"
"testing"

"aoc/utils"
)

var testInput = `p=0,4 v=3,-3
p=6,3 v=-1,-3
p=10,3 v=-1,2
p=2,0 v=2,-1
p=0,0 v=1,3
p=3,0 v=-2,-2
p=7,6 v=-1,-3
p=3,0 v=-1,-2
p=9,3 v=2,3
p=7,3 v=-1,2
p=2,4 v=2,-3
p=9,5 v=-3,-3`

func TestSolve(t *testing.T) {
tests := []struct {
input string
answer int
}{
{testInput, 0},
}

if testing.Verbose() {
utils.Verbose = true
}

for _, test := range tests {
r := strings.NewReader(test.input)

result := Solve(r).(int)

if result != test.answer {
t.Errorf("Expected %d, got %d", test.answer, result)
}
}
}

0 comments on commit 5e89d61

Please sign in to comment.