code.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. for _, robot := range robots {
  43. robot.x = (robot.vX*after + robot.x) % maxX
  44. robot.y = (robot.vY*after + robot.y) % maxY
  45. }
  46. return robots
  47. }
  48. func part1(robots []Robot, maxX, maxY, after int) int {
  49. midX := maxX / 2
  50. midY := maxY / 2
  51. var count int
  52. robotsMoved := robotsAfter(robots, maxX, maxY, after)
  53. fmt.Println(robotsMoved)
  54. for _, robot := range robotsMoved {
  55. if robot.x != midX && robot.y != midY {
  56. count++
  57. }
  58. }
  59. return count
  60. }
  61. func main() {
  62. if len(os.Args) < 2 {
  63. log.Fatal("You need to specify a file!")
  64. }
  65. filePath := os.Args[1]
  66. file, err := os.Open(filePath)
  67. if err != nil {
  68. log.Fatalf("Failed to open %s!\n", filePath)
  69. }
  70. robots := readInput(file)
  71. maxX, maxY := getMaxXY(robots)
  72. fmt.Println(maxX, maxY)
  73. fmt.Println("Part1:", part1(robots, maxX, maxY, 100))
  74. }