code.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 count int
  60. robotsMoved := robotsAfter(robots, maxX, maxY, after)
  61. fmt.Println(robotsMoved)
  62. for _, robot := range robotsMoved {
  63. if robot.x != midX && robot.y != midY {
  64. count++
  65. }
  66. }
  67. return count
  68. }
  69. func main() {
  70. if len(os.Args) < 2 {
  71. log.Fatal("You need to specify a file!")
  72. }
  73. filePath := os.Args[1]
  74. file, err := os.Open(filePath)
  75. if err != nil {
  76. log.Fatalf("Failed to open %s!\n", filePath)
  77. }
  78. robots := readInput(file)
  79. maxX, maxY := getMaxXY(robots)
  80. fmt.Println(maxX, maxY)
  81. fmt.Println("Part1:", part1(robots, maxX, maxY, 100))
  82. }