code.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. was := dial
  42. if rotation.Direction == 'L' {
  43. dial -= rotation.Clicks
  44. } else {
  45. dial += rotation.Clicks
  46. }
  47. if dial > 100 {
  48. passedZeros += dial / 100
  49. }
  50. if dial < 0 {
  51. fmt.Println(was, dial, rotation, passedZeros)
  52. if abs(dial) > 100 {
  53. passedZeros += abs(dial) / 100
  54. }
  55. if rotation.Clicks != abs(dial) {
  56. passedZeros++
  57. }
  58. fmt.Println(was, dial, rotation, passedZeros)
  59. }
  60. dial %= 100
  61. if dial < 0 {
  62. dial += 100
  63. }
  64. if dial == 0 {
  65. zeros++
  66. }
  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. }