code.go 1.3 KB

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