-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
75 lines (59 loc) · 1.35 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Package day04 - Solution for Advent of Code 2022/04
// Problem Link: http://adventofcode.com/2022/day/04
package day04
import (
_ "embed"
"fmt"
"github.com/code-shoily/aocgo/io"
)
//go:embed input.txt
var input string
// Run prints out the result of the solution.
func Run() {
fmt.Println(solve(input))
}
func solve(input string) (int, int) {
sections := parse(input)
return solvePart1(sections), solvePart2(sections)
}
func solvePart1(sections [][4]int) (total int) {
for _, ranges := range sections {
if hasContained(ranges) {
total++
}
}
return total
}
func solvePart2(sections [][4]int) (total int) {
for _, ranges := range sections {
if hasOverlap(ranges) {
total++
}
}
return total
}
func parse(input string) (data [][4]int) {
for _, line := range io.SplitLines(input) {
data = append(data, parseSections(line))
}
return data
}
func parseSections(line string) [4]int {
var from1, to1, from2, to2 int
fmt.Sscanf(line, "%d-%d,%d-%d", &from1, &to1, &from2, &to2)
return [4]int{from1, to1, from2, to2}
}
func hasContained(ranges [4]int) bool {
x1 := ranges[0]
y1 := ranges[1]
x2 := ranges[2]
y2 := ranges[3]
return x1 <= x2 && y1 >= y2 || x2 <= x1 && y2 >= y1
}
func hasOverlap(ranges [4]int) bool {
x1 := ranges[0]
y1 := ranges[1]
x2 := ranges[2]
y2 := ranges[3]
return x1 <= x2 && y1 >= x2 || x2 <= x1 && y2 >= x1
}