Skip to content

Commit fede8e9

Browse files
author
Robb Kidd
committed
refactor to types and a function
1 parent ddfc88f commit fede8e9

File tree

1 file changed

+34
-13
lines changed

1 file changed

+34
-13
lines changed

2022/go/day04/main.go

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,48 @@ func main() {
1717
func p1(lines []string) int {
1818
var fullyCovered int
1919
for _, line := range lines {
20-
pair := strings.Split(line, ",")
21-
left := strings.Split(pair[0], "-")
22-
right := strings.Split(pair[1], "-")
23-
leftStart, _ := strconv.Atoi(left[0])
24-
leftStop, _ := strconv.Atoi(left[1])
25-
rightStart, _ := strconv.Atoi(right[0])
26-
rightStop, _ := strconv.Atoi(right[1])
27-
28-
if leftStart >= rightStart && leftStop <= rightStop {
29-
fullyCovered++
30-
continue
31-
}
20+
pair := lineToPair(line)
3221

33-
if leftStart <= rightStart && leftStop >= rightStop {
22+
if fullyCovers(pair) {
3423
fullyCovered++
3524
continue
3625
}
3726
}
3827
return fullyCovered
3928
}
4029

30+
func fullyCovers(pair Pair) bool {
31+
if pair.left.start >= pair.right.start && pair.left.stop <= pair.right.stop {
32+
return true
33+
}
34+
if pair.left.start <= pair.right.start && pair.left.stop >= pair.right.stop {
35+
return true
36+
}
37+
return false
38+
}
39+
40+
func lineToPair(line string) Pair {
41+
p := strings.Split(line, ",")
42+
left := strings.Split(p[0], "-")
43+
right := strings.Split(p[1], "-")
44+
45+
leftStart, _ := strconv.Atoi(left[0])
46+
leftStop, _ := strconv.Atoi(left[1])
47+
rightStart, _ := strconv.Atoi(right[0])
48+
rightStop, _ := strconv.Atoi(right[1])
49+
50+
return Pair{
51+
left: Assignment{
52+
start: leftStart,
53+
stop: leftStop,
54+
},
55+
right: Assignment{
56+
start: rightStart,
57+
stop: rightStop,
58+
},
59+
}
60+
}
61+
4162
func p2(input []string) int {
4263
return 0
4364
}

0 commit comments

Comments
 (0)