Created
December 4, 2022 10:17
-
-
Save Roemerb/48fbeb3c1bca5f1ab0f3b1611f254657 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package day4 | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
"strings" | |
) | |
type Assignment struct { | |
from int | |
to int | |
} | |
type Pair struct { | |
a Assignment | |
b Assignment | |
} | |
func Run() { | |
pairs := getPairsFromInput("./day4/4.txt") | |
fmt.Println("Subsets found: ", getSubsetCount(pairs)) | |
fmt.Println("Partial subsets found: ", findOverlaps(pairs)) | |
} | |
func getPairsFromInput(path string) []Pair { | |
content, err := os.Open(path) | |
if err != nil { | |
log.Fatal("Cannot read input: ", err) | |
} | |
scanner := bufio.NewScanner(content) | |
scanner.Split(bufio.ScanLines) | |
var pairs []Pair | |
for scanner.Scan() { | |
line := scanner.Text() | |
assignments := strings.Split(line, ",") | |
if len(assignments) != 2 { | |
log.Fatal("Invalid pair: ", line) | |
} | |
sectionsA := strings.Split(assignments[0], "-") | |
aFrom, _ := strconv.Atoi(sectionsA[0]) | |
aTo, _ := strconv.Atoi(sectionsA[1]) | |
sectionsB := strings.Split(assignments[1], "-") | |
bFrom, _ := strconv.Atoi(sectionsB[0]) | |
bTo, _ := strconv.Atoi(sectionsB[1]) | |
pairs = append(pairs, Pair{ | |
a: Assignment{from: aFrom, to: aTo}, | |
b: Assignment{from: bFrom, to: bTo}, | |
}) | |
} | |
return pairs | |
} | |
func getSubsetCount(pairs []Pair) int { | |
var count int = 0 | |
for _, pair := range pairs { | |
if isSubset(pair.a, pair.b) || isSubset(pair.b, pair.a) { | |
count++ | |
} | |
} | |
return count | |
} | |
func findOverlaps(pairs []Pair) int { | |
var count int = 0 | |
for _, pair := range pairs { | |
if assignmentOverlaps(pair.a, pair.b) || assignmentOverlaps(pair.b, pair.a) { | |
count++ | |
} | |
} | |
return count | |
} | |
func isSubset(a Assignment, b Assignment) bool { | |
return a.from >= b.from && a.to <= b.to | |
} | |
// assignmentOverlaps tells you if the two assignments | |
// at least partially overlap. I found it easier to check | |
// if the assignments DON'T overlap rather than if they do | |
// so I return the inverse of that. | |
// | |
// Assignments don't overlap if A ends before B begins OR | |
// A begins after B ends. | |
func assignmentOverlaps(a Assignment, b Assignment) bool { | |
return !(a.to < b.from || a.from > b.to) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment