code.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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) 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 i
  38. }
  39. if direction == 0 {
  40. direction = delta
  41. } else if direction < 0 && delta > 0 || direction > 0 && delta < 0 {
  42. return i
  43. }
  44. }
  45. return 0
  46. }
  47. func checkReports(reports [][]int) (int, int) {
  48. var part1, part2 int
  49. for _, report := range reports {
  50. bad := safe(report)
  51. if bad == 0 {
  52. part1++
  53. } else {
  54. bad = safe(append(report[:bad], report[bad+1:]...))
  55. if bad == 0 {
  56. part2++
  57. }
  58. }
  59. }
  60. return part1, part2
  61. }
  62. func main() {
  63. if len(os.Args) < 2 {
  64. log.Fatal("You need to specify a file!")
  65. }
  66. filePath := os.Args[1]
  67. file, err := os.Open(filePath)
  68. if err != nil {
  69. log.Fatalf("Failed to open %s!\n", filePath)
  70. }
  71. reports := readInput(file)
  72. part1, part2 := checkReports(reports)
  73. fmt.Println("Part1:", part1)
  74. fmt.Println("Part2:", part1+part2)
  75. }