code.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 second[0] >= first[0] && second[0] <= first[1] && second[1] >= first[0] && 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 overlaps(first [2]int, second [2]int) bool {
  45. if second[0] >= first[0] && second[0] <= first[1] || second[1] >= first[0] && second[1] <= first[1] {
  46. return true
  47. }
  48. return false
  49. }
  50. func part2(pairs []pair) int {
  51. count := 0
  52. for i := range pairs {
  53. if overlaps(pairs[i].first, pairs[i].second) || overlaps(pairs[i].second, pairs[i].first) {
  54. count++
  55. }
  56. }
  57. return count
  58. }
  59. func main() {
  60. if len(os.Args) < 2 {
  61. log.Fatal("You need to specify a file!")
  62. }
  63. filePath := os.Args[1]
  64. file, err := os.Open(filePath)
  65. if err != nil {
  66. log.Fatalf("Failed to open %s!\n", filePath)
  67. }
  68. pairs := readInput(file)
  69. fmt.Println("Part1:", part1(pairs))
  70. fmt.Println("Part2:", part2(pairs))
  71. }