code.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 check(a, b int, direction int) (bool, int) {
  32. delta := b - a
  33. if delta == 0 || delta < -3 || delta > 3 {
  34. return false, direction
  35. }
  36. if direction == 0 {
  37. direction = delta
  38. } else if direction < 0 && delta > 0 || direction > 0 && delta < 0 {
  39. return false, direction
  40. }
  41. return true, direction
  42. }
  43. func safe(report []int, skip bool) bool {
  44. var direction int
  45. var status bool
  46. edge := len(report)
  47. for i := 1; i < edge; i++ {
  48. status, direction = check(report[i], report[i-1], direction)
  49. if !status {
  50. if skip && i+1 < edge {
  51. status, direction = check(report[i+1], report[i-1], direction)
  52. if status {
  53. i++
  54. skip = false
  55. continue
  56. }
  57. }
  58. return false
  59. }
  60. }
  61. return true
  62. }
  63. func part(reports [][]int, skip bool) int {
  64. var result int
  65. for _, report := range reports {
  66. if safe(report, skip) {
  67. result++
  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:", part(reports, false))
  83. fmt.Println("Part2:", part(reports, true))
  84. }