github.com/mnlphlp/aoc22@v0.0.0-20230330151331-c1dc4bff1b9b/day04/day04.go (about)

     1  package day04
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"strings"
     7  )
     8  
     9  type secRange struct {
    10  	start int
    11  	end   int
    12  }
    13  
    14  type pair [2]secRange
    15  
    16  func (p pair) fullyOverlap() bool {
    17  	return p[0].start >= p[1].start && p[0].end <= p[1].end || p[1].start >= p[0].start && p[1].end <= p[0].end
    18  }
    19  
    20  func (p pair) overlap() bool {
    21  	return p[0].start >= p[1].start && p[0].start <= p[1].end || p[1].start >= p[0].start && p[1].start <= p[0].end
    22  }
    23  
    24  func parseInput(input string) []pair {
    25  	lines := strings.Split(string(input), "\n")
    26  	lines = lines[:len(lines)-1]
    27  	pairs := make([]pair, len(lines))
    28  	for i, line := range lines {
    29  		ranges := strings.Split(line, ",")
    30  		for j, r := range ranges {
    31  			sec := strings.Split(r, "-")
    32  			start, _ := strconv.Atoi(sec[0])
    33  			end, _ := strconv.Atoi(sec[1])
    34  			pairs[i][j] = secRange{start, end}
    35  		}
    36  	}
    37  	return pairs
    38  }
    39  
    40  func Solve(input string, test bool, task int) (string, string) {
    41  	pairs := parseInput(input)
    42  	res1, res2 := "", ""
    43  	count := 0
    44  
    45  	if task != 2 {
    46  		for _, p := range pairs {
    47  			if p.fullyOverlap() {
    48  				count++
    49  			}
    50  		}
    51  		fmt.Printf("fully overlapping pairs: %v\n", count)
    52  		res1 = strconv.Itoa(count)
    53  	}
    54  	if task != 1 {
    55  		count = 0
    56  		for _, p := range pairs {
    57  			if p.overlap() {
    58  				count++
    59  			}
    60  		}
    61  		fmt.Printf("overlapping pairs: %v\n", count)
    62  		res2 = strconv.Itoa(count)
    63  	}
    64  	return res1, res2
    65  }