code.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. func readInput(file *os.File) [][]int {
  11. scanner := bufio.NewScanner(file)
  12. var reports [][]int
  13. for scanner.Scan() {
  14. line := scanner.Text()
  15. if line == "" {
  16. break
  17. }
  18. var report []int
  19. numbers := strings.Split(line, " ")
  20. for _, number := range numbers {
  21. level, err := strconv.Atoi(number)
  22. if err != nil {
  23. log.Fatalf("Problem parsing input: %s", err)
  24. }
  25. report = append(report, level)
  26. }
  27. reports = append(reports, report)
  28. }
  29. return reports
  30. }
  31. func safe(report []int) (bool, int) {
  32. var direction int
  33. edge := len(report)
  34. for i := 1; i < edge; i++ {
  35. delta := report[i] - report[i-1]
  36. if delta == 0 || delta < -3 || delta > 3 {
  37. return false, i
  38. }
  39. if direction == 0 {
  40. direction = delta
  41. } else if direction < 0 && delta > 0 || direction > 0 && delta < 0 {
  42. return false, i
  43. }
  44. }
  45. return true, 0
  46. }
  47. func part1(reports [][]int) int {
  48. var result int
  49. for _, report := range reports {
  50. status, _ := safe(report)
  51. if status {
  52. result++
  53. }
  54. }
  55. return result
  56. }
  57. func part2(reports [][]int) int {
  58. var result int
  59. for _, report := range reports {
  60. status, failed := safe(report)
  61. if status {
  62. result++
  63. } else {
  64. status, failed = safe(append(report[:failed], report[failed+1:]...))
  65. if status {
  66. result++
  67. }
  68. }
  69. }
  70. return result
  71. }
  72. func main() {
  73. if len(os.Args) < 2 {
  74. log.Fatal("You need to specify a file!")
  75. }
  76. filePath := os.Args[1]
  77. file, err := os.Open(filePath)
  78. if err != nil {
  79. log.Fatalf("Failed to open %s!\n", filePath)
  80. }
  81. reports := readInput(file)
  82. fmt.Println("Part1:", part1(reports))
  83. fmt.Println("Part2:", part2(reports))
  84. }