code.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type pair struct {
  9. first [2]int
  10. second [2]int
  11. }
  12. func readInput(file *os.File) []pair {
  13. scanner := bufio.NewScanner(file)
  14. var pairs []pair
  15. for scanner.Scan() {
  16. line := scanner.Text()
  17. if line == "" {
  18. continue
  19. }
  20. current := pair{}
  21. n, err := fmt.Sscanf(line, "%d-%d,%d-%d", &current.first[0], &current.first[1], &current.second[0], &current.second[1])
  22. if n != 4 || err != nil {
  23. log.Fatal("Problem reading input:", err)
  24. }
  25. pairs = append(pairs, current)
  26. }
  27. return pairs
  28. }
  29. func contains(first [2]int, second [2]int) bool {
  30. if first[0] >= second[0] && second[0] < first[1] && first[0] > second[1] && second[1] <= first[1] {
  31. return true
  32. }
  33. return false
  34. }
  35. func part1(pairs []pair) int {
  36. count := 0
  37. for i := range pairs {
  38. if contains(pairs[i].first, pairs[i].second) || contains(pairs[i].second, pairs[i].first) {
  39. count++
  40. }
  41. }
  42. return count
  43. }
  44. func main() {
  45. if len(os.Args) < 2 {
  46. log.Fatal("You need to specify a file!")
  47. }
  48. filePath := os.Args[1]
  49. file, err := os.Open(filePath)
  50. if err != nil {
  51. log.Fatalf("Failed to open %s!\n", filePath)
  52. }
  53. pairs := readInput(file)
  54. fmt.Println("Part1:", part1(pairs))
  55. }