-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
116 lines (104 loc) · 1.99 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"bufio"
"io"
"sort"
"strconv"
"strings"
)
func fs1(input io.Reader) (int, error) {
scanner := bufio.NewScanner(input)
var ranges []Range
for scanner.Scan() {
s := scanner.Text()
idx := strings.Index(s, "-")
min, err := strconv.Atoi(s[:idx])
if err != nil {
return 0, err
}
max, err := strconv.Atoi(s[idx+1:])
if err != nil {
return 0, err
}
ranges = append(ranges, Range{min, max})
}
sort.Slice(ranges, func(i, j int) bool {
a := ranges[i]
b := ranges[j]
if a.min < b.min {
return true
}
if b.max < a.max {
return false
}
return a.max <= b.max
})
var merged []Range
last := ranges[0]
for i := 1; i < len(ranges); i++ {
rng := ranges[i]
if rng.min <= last.max || rng.min == last.max+1 {
last = Range{last.min, max(last.max, rng.max)}
} else {
merged = append(merged, last)
last = rng
}
}
merged = append(merged, last)
return merged[0].max + 1, nil
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
type Range struct {
min int
max int
}
func fs2(input io.Reader, maxRange int) (int, error) {
scanner := bufio.NewScanner(input)
var ranges []Range
for scanner.Scan() {
s := scanner.Text()
idx := strings.Index(s, "-")
min, err := strconv.Atoi(s[:idx])
if err != nil {
return 0, err
}
max, err := strconv.Atoi(s[idx+1:])
if err != nil {
return 0, err
}
ranges = append(ranges, Range{min, max})
}
sort.Slice(ranges, func(i, j int) bool {
a := ranges[i]
b := ranges[j]
if a.min < b.min {
return true
}
if b.min < a.min {
return false
}
return a.max <= b.max
})
var merged []Range
last := ranges[0]
for i := 1; i < len(ranges); i++ {
rng := ranges[i]
if rng.min <= last.max || rng.min == last.max+1 {
last = Range{last.min, max(last.max, rng.max)}
} else {
merged = append(merged, last)
last = rng
}
}
merged = append(merged, last)
sum := 0
for _, rng := range merged {
sum += rng.max - rng.min + 1
}
return maxRange - sum + 1, nil
}