code.go 1.5 KB

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