code.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 bigger(a, b int) int {
  32. if a > b {
  33. return a
  34. }
  35. return b
  36. }
  37. func check(arr []int, direction int) (bool, bool) {
  38. edge := len(arr)
  39. lengths := make([]int, edge)
  40. for k := 0; k < edge; k++ {
  41. lengths[k] = 1
  42. for i := 0; i < k; i++ {
  43. delta := arr[k] - arr[i]
  44. if direction < 0 && delta > 0 || direction > 0 && delta < 0 {
  45. continue
  46. }
  47. if delta != 0 && delta <= 3 && delta >= -3 {
  48. lengths[k] = bigger(lengths[k], lengths[i]+1)
  49. }
  50. }
  51. }
  52. return lengths[edge-1] == edge, lengths[edge-1] == edge-1
  53. }
  54. func checkReports(reports [][]int) (int, int) {
  55. var part1, part2 int
  56. for _, report := range reports {
  57. direction := report[1] - report[0]
  58. one, two := check(report, direction)
  59. if one {
  60. part1++
  61. continue
  62. } else if two {
  63. part2++
  64. continue
  65. }
  66. one, two = check(report, -direction)
  67. if one {
  68. part1++
  69. continue
  70. } else if two {
  71. part2++
  72. }
  73. }
  74. return part1, part2
  75. }
  76. func main() {
  77. if len(os.Args) < 2 {
  78. log.Fatal("You need to specify a file!")
  79. }
  80. filePath := os.Args[1]
  81. file, err := os.Open(filePath)
  82. if err != nil {
  83. log.Fatalf("Failed to open %s!\n", filePath)
  84. }
  85. reports := readInput(file)
  86. part1, part2 := checkReports(reports)
  87. fmt.Println("Part1:", part1)
  88. fmt.Println("Part2:", part1+part2)
  89. }