code.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type Robot struct {
  9. x, y int
  10. vX, vY int
  11. }
  12. func readInput(file *os.File) []Robot {
  13. scanner := bufio.NewScanner(file)
  14. var robots []Robot
  15. for scanner.Scan() {
  16. line := scanner.Text()
  17. if line == "" {
  18. break
  19. }
  20. var robot Robot
  21. n, err := fmt.Sscanf(line, "p=%d,%d v=%d,%d", &robot.x, &robot.y, &robot.vX, &robot.vY)
  22. if n != 4 || err != nil {
  23. log.Fatalf("Not able to parse robot '%s': %s", line, err)
  24. }
  25. robots = append(robots, robot)
  26. }
  27. return robots
  28. }
  29. func getMaxXY(robots []Robot) (int, int) {
  30. var maxX, maxY int
  31. for _, robot := range robots {
  32. if robot.x > maxX {
  33. maxX = robot.x
  34. }
  35. if robot.y > maxY {
  36. maxY = robot.y
  37. }
  38. }
  39. return maxX + 1, maxY + 1
  40. }
  41. func robotsAfter(robots []Robot, maxX, maxY, after int) []Robot {
  42. robotsMoved := make([]Robot, len(robots))
  43. for i, robot := range robots {
  44. robot.x = (robot.vX*after + robot.x) % maxX
  45. if robot.x < 0 {
  46. robot.x = maxX + robot.x
  47. }
  48. robot.y = (robot.vY*after + robot.y) % maxY
  49. if robot.y < 0 {
  50. robot.y = maxY + robot.y
  51. }
  52. robotsMoved[i] = robot
  53. }
  54. return robotsMoved
  55. }
  56. func part1(robots []Robot, maxX, maxY, after int) int {
  57. midX := maxX / 2
  58. midY := maxY / 2
  59. var q1, q2, q3, q4 int
  60. robotsMoved := robotsAfter(robots, maxX, maxY, after)
  61. for _, robot := range robotsMoved {
  62. if robot.x < midX && robot.y < midY {
  63. q1++
  64. }
  65. if robot.x > midX && robot.y < midY {
  66. q2++
  67. }
  68. if robot.x < midX && robot.y > midY {
  69. q3++
  70. }
  71. if robot.x > midX && robot.y > midY {
  72. q4++
  73. }
  74. }
  75. return q1 * q2 * q3 * q4
  76. }
  77. func main() {
  78. if len(os.Args) < 2 {
  79. log.Fatal("You need to specify a file!")
  80. }
  81. filePath := os.Args[1]
  82. file, err := os.Open(filePath)
  83. if err != nil {
  84. log.Fatalf("Failed to open %s!\n", filePath)
  85. }
  86. robots := readInput(file)
  87. maxX, maxY := getMaxXY(robots)
  88. fmt.Println("Part1:", part1(robots, maxX, maxY, 100))
  89. }