123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package main
- import (
- "bufio"
- "fmt"
- "log"
- "os"
- )
- type pair struct {
- first [2]int
- second [2]int
- }
- func readInput(file *os.File) []pair {
- scanner := bufio.NewScanner(file)
- var pairs []pair
- for scanner.Scan() {
- line := scanner.Text()
- if line == "" {
- continue
- }
- current := pair{}
- n, err := fmt.Sscanf(line, "%d-%d,%d-%d", ¤t.first[0], ¤t.first[1], ¤t.second[0], ¤t.second[1])
- if n != 4 || err != nil {
- log.Fatal("Problem reading input:", err)
- }
- pairs = append(pairs, current)
- }
- return pairs
- }
- func contains(first [2]int, second [2]int) bool {
- if second[0] >= first[0] && second[0] <= first[1] && second[1] >= first[0] && second[1] <= first[1] {
- return true
- }
- return false
- }
- func part1(pairs []pair) int {
- count := 0
- for i := range pairs {
- if contains(pairs[i].first, pairs[i].second) || contains(pairs[i].second, pairs[i].first) {
- count++
- }
- }
- return count
- }
- func overlaps(first [2]int, second [2]int) bool {
- if second[0] >= first[0] && second[0] <= first[1] || second[1] >= first[0] && second[1] <= first[1] {
- return true
- }
- return false
- }
- func part2(pairs []pair) int {
- count := 0
- for i := range pairs {
- if overlaps(pairs[i].first, pairs[i].second) || overlaps(pairs[i].second, pairs[i].first) {
- count++
- }
- }
- return count
- }
- func main() {
- if len(os.Args) < 2 {
- log.Fatal("You need to specify a file!")
- }
- filePath := os.Args[1]
- file, err := os.Open(filePath)
- if err != nil {
- log.Fatalf("Failed to open %s!\n", filePath)
- }
- pairs := readInput(file)
- fmt.Println("Part1:", part1(pairs))
- fmt.Println("Part2:", part2(pairs))
- }
|