code.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. changed := rotation.Clicks / 100
  42. left := rotation.Clicks % 100
  43. if rotation.Direction == 'L' {
  44. dial -= left
  45. } else {
  46. dial += left
  47. }
  48. if dial > 100 {
  49. passedZeros++
  50. }
  51. if dial < 0 {
  52. if left != abs(dial) {
  53. passedZeros++
  54. }
  55. }
  56. dial %= 100
  57. if dial < 0 {
  58. dial += 100
  59. }
  60. if dial == 0 {
  61. if changed > 0 && rotation.Clicks%100 == 0 {
  62. changed -= 1
  63. }
  64. zeros++
  65. }
  66. passedZeros += changed
  67. }
  68. return zeros, passedZeros
  69. }
  70. func main() {
  71. if len(os.Args) < 2 {
  72. log.Fatal("You need to specify a file!")
  73. }
  74. filePath := os.Args[1]
  75. file, err := os.Open(filePath)
  76. if err != nil {
  77. log.Fatalf("Failed to open %s!\n", filePath)
  78. }
  79. rotations := readInput(file)
  80. zeros, passedZeros := parts(rotations)
  81. fmt.Println("Part1:", zeros)
  82. fmt.Println("Part2:", zeros+passedZeros)
  83. }