code.go 1.5 KB

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