code.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type Rotation struct {
  9. Direction byte
  10. Clicks int
  11. }
  12. func readInput(file *os.File) []Rotation {
  13. scanner := bufio.NewScanner(file)
  14. var rotations []Rotation
  15. for scanner.Scan() {
  16. line := scanner.Text()
  17. if line == "" {
  18. break
  19. }
  20. var direction byte
  21. var clicks int
  22. n, err := fmt.Sscanf(line, "%c%d", &direction, &clicks)
  23. if n != 2 || err != nil {
  24. log.Fatalf("Bad input: %s", line)
  25. }
  26. rotations = append(rotations, Rotation{Direction: direction, Clicks: clicks})
  27. }
  28. return rotations
  29. }
  30. func abs(x int) int {
  31. if x < 0 {
  32. return -x
  33. }
  34. return x
  35. }
  36. func parts(rotations []Rotation) (int, int) {
  37. var zeros int
  38. var passedZeros int
  39. dial := 50
  40. for _, rotation := range rotations {
  41. if rotation.Direction == 'L' {
  42. dial -= rotation.Clicks
  43. } else {
  44. dial += rotation.Clicks
  45. }
  46. if dial > 100 {
  47. passedZeros += dial / 100
  48. if dial%100 == 0 {
  49. passedZeros--
  50. }
  51. }
  52. if dial < 0 {
  53. if abs(dial) > 100 {
  54. passedZeros += abs(dial) / 100
  55. }
  56. if rotation.Clicks != abs(dial) {
  57. passedZeros++
  58. }
  59. if dial%100 == 0 {
  60. passedZeros--
  61. }
  62. }
  63. dial %= 100
  64. if dial < 0 {
  65. dial += 100
  66. }
  67. if dial == 0 {
  68. zeros++
  69. }
  70. }
  71. return zeros, passedZeros
  72. }
  73. func main() {
  74. if len(os.Args) < 2 {
  75. log.Fatal("You need to specify a file!")
  76. }
  77. filePath := os.Args[1]
  78. file, err := os.Open(filePath)
  79. if err != nil {
  80. log.Fatalf("Failed to open %s!\n", filePath)
  81. }
  82. rotations := readInput(file)
  83. zeros, passedZeros := parts(rotations)
  84. fmt.Println("Part1:", zeros)
  85. fmt.Println("Part2:", zeros+passedZeros)
  86. }