code.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 removeAt(arr []int, index int) []int {
  48. ret := make([]int, 0)
  49. ret = append(ret, arr[:index]...)
  50. return append(ret, arr[index+1:]...)
  51. }
  52. func checkReports(reports [][]int) (int, int) {
  53. var part1, part2 int
  54. for _, report := range reports {
  55. bad := safe(report)
  56. if bad == 0 {
  57. part1++
  58. } else {
  59. bad = safe(removeAt(report, bad))
  60. if bad == 0 {
  61. part2++
  62. }
  63. }
  64. }
  65. return part1, part2
  66. }
  67. func main() {
  68. if len(os.Args) < 2 {
  69. log.Fatal("You need to specify a file!")
  70. }
  71. filePath := os.Args[1]
  72. file, err := os.Open(filePath)
  73. if err != nil {
  74. log.Fatalf("Failed to open %s!\n", filePath)
  75. }
  76. reports := readInput(file)
  77. part1, part2 := checkReports(reports)
  78. fmt.Println("Part1:", part1)
  79. fmt.Println("Part2:", part1+part2)
  80. }