diff --git a/day14p1/solution.go b/day14p1/solution.go new file mode 100644 index 0000000..32e168e --- /dev/null +++ b/day14p1/solution.go @@ -0,0 +1,66 @@ +package day14p1 + +import ( + "io" + + "aoc/utils" +) + +func Solve(r io.Reader) any { + lines := utils.ReadLines(r) + isTest := len(lines) == 12 + boardWidth := 11 + if !isTest { + boardWidth = 101 + } + boardHeight := 7 + if !isTest { + boardHeight = 103 + } + + endPoints := make(map[utils.Point]int) + + for _, line := range lines { + ints := utils.GetInts(line) + px, py, vx, vy := ints[0], ints[1], ints[2], ints[3] + for range 100 { + px += vx + py += vy + if px < 0 { + px += boardWidth + } else if px >= boardWidth { + px -= boardWidth + } + if py < 0 { + py += boardHeight + } else if py >= boardHeight { + py -= boardHeight + } + } + endPoints[utils.Point{X: px, Y: py}]++ + } + + bots := make([]int, 4) + + for point, count := range endPoints { + if point.X < boardWidth/2 && point.Y < boardHeight/2 { + bots[0] += count + } else if point.X > boardWidth/2 && point.Y < boardHeight/2 { + bots[1] += count + } else if point.X < boardWidth/2 && point.Y > boardHeight/2 { + bots[2] += count + } else if point.X > boardWidth/2 && point.Y > boardHeight/2 { + bots[3] += count + } + } + + return multAll(bots) +} + +func multAll(arr []int) int { + result := 1 + for _, n := range arr { + result *= n + } + return result +} diff --git a/day14p1/solution_test.go b/day14p1/solution_test.go new file mode 100644 index 0000000..1c9728f --- /dev/null +++ b/day14p1/solution_test.go @@ -0,0 +1,44 @@ +package day14p1 + +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, 12}, + } + + 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) + } + } +} diff --git a/utils/functions.go b/utils/functions.go index 0b1a4bf..2501286 100644 --- a/utils/functions.go +++ b/utils/functions.go @@ -6,8 +6,13 @@ import ( "bufio" "fmt" "io" + "regexp" + "strconv" ) +// regex for integers +var intRegex = regexp.MustCompile(`-?\d+`) + // Greatest Common Denominator func Gcd(a, b int64) int64 { for b != 0 { @@ -55,3 +60,20 @@ func ReadLines(r io.Reader) []string { return result } + +func GetInts(s string) []int { + matches := intRegex.FindAllString(s, -1) + result := make([]int, len(matches)) + for i, match := range matches { + result[i] = Atoi(match) + } + + return result +} + +func Atoi(s string) int { + result, err := strconv.Atoi(s) + Check(err, "error converting %s to int", s) + + return result +}