-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
158 lines (147 loc) · 2.39 KB
/
parse.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package aoc
import (
"strings"
"unicode"
)
func Ints(l string) []int {
return ReadInts(NumberStrings(l))
}
func ReadInts(in []string) []int {
r := make([]int, len(in))
for i, s := range in {
r[i] = MustParseInt(s)
}
return r
}
func NumberStrings(s string) []string {
n := NumberString(s)
f := func(c rune) bool {
return !(unicode.IsNumber(c) || c == '-')
}
return strings.FieldsFunc(n, f)
}
func NumberString(s string) string {
n := ""
for i := 0; i < len(s); i++ {
if s[i] == '-' &&
(i == len(s)-1 || !unicode.IsNumber(rune(s[i+1]))) {
n += " "
} else {
n += string(s[i])
}
}
return n
}
func FastInts(l []byte, expected int) []int {
res := make([]int, 0, expected)
n := 0
num := false
for _, ch := range l {
if ch >= '0' && ch <= '9' {
num = true
n = n*10 + int(ch&0xf)
} else if num {
res = append(res, n)
n = 0
num = false
}
}
if num {
res = append(res, n)
}
return res
}
func FastSignedInts(l []byte, expected int) []int {
res := make([]int, 0, expected)
n := 0
m := 1
num := false
for _, ch := range l {
if ch == '-' {
m = -1
} else if ch >= '0' && ch <= '9' {
num = true
n = n*10 + int(ch&0xf)
} else if num {
res = append(res, n*m)
n = 0
m = 1
num = false
}
}
if num {
res = append(res, n*m)
}
return res
}
func FastBytes(l []byte) []byte {
res := l[:0]
var n byte
num := false
for _, ch := range l {
if ch >= '0' && ch <= '9' {
num = true
n = n*10 + (ch & 0xf)
} else if num {
res = append(res, n)
n = 0
num = false
}
}
if num {
res = append(res, n)
}
return res
}
func FastInt64s(l []byte, expected int) []int64 {
res := make([]int64, 0, expected)
var n int64
var m int64 = 1
num := false
for _, ch := range l {
if ch == '-' {
m = -1
} else if ch >= '0' && ch <= '9' {
num = true
n = n*10 + int64(ch&0xf)
} else if num {
res = append(res, n*m)
n = 0
m = 1
num = false
}
}
if num {
res = append(res, n*m)
}
return res
}
func ScanUint(in []byte, i int) (int, int) {
n := 0
j := i
for ; j < len(in); j++ {
if in[j] >= '0' && in[j] <= '9' {
n = n*10 + int(in[j]&0xf)
} else {
break
}
}
return n, j
}
func ScanInt(in []byte, i int) (int, int) {
n := 0
j := i
m := 1
if in[j] == '-' {
m = -1
j++
}
for ; j < len(in); j++ {
if in[j] >= '0' && in[j] <= '9' {
n = n*10 + int(in[j]&0xf)
} else {
break
}
}
return n * m, j
}