Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
273 lines (224 loc) · 5.65 KB
/
Copy pathmain.go
File metadata and controls
273 lines (224 loc) · 5.65 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
)
const (
DefaultOutputFile = "input.txt"
DefaultInputFile = "raw.txt"
FilePermission = 0644
)
var name = flag.String("p", "", "The suffix name of the file to write to")
var inputFile = flag.String("i", "raw.txt", "The input file to read from")
var verbose = flag.Bool("v", false, "Enable verbose output")
var companion = flag.Bool("companion", false, "Export to competitive companion format")
var outputFile = flag.String("o", DefaultOutputFile, "The output file to write to")
var inputPrefixes = []string{"输入:", "输入:", "Input: ", "Input:"}
type TestCase struct {
Test string `json:"test"`
}
type TestCases struct {
TestCases []TestCase `json:"testcases"`
}
func main() {
flag.Parse()
err := validateFlags()
if err != nil {
log.Fatalf("Error validating flags: %v\n", err)
}
err = processFile(*inputFile, *outputFile)
if err != nil {
log.Fatalf("Error processing file: %v\n", err)
}
if *name != "" {
logf("Backing up file with suffix: %s\n", *name)
err = backupFile(*name)
if err != nil {
log.Fatalf("Error backing up file: %v\n", err)
}
}
}
func processFile(inputPath, outputPath string) error {
readFh, err := os.Open(inputPath)
if err != nil {
log.Fatalf("Error opening input file: %v\n", err)
}
defer readFh.Close()
writeFh, err := os.OpenFile(outputPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, FilePermission)
if err != nil {
log.Fatalf("Error opening output file: %v\n", err)
}
defer writeFh.Close()
return processLines(readFh, writeFh)
}
func processLines(reader io.Reader, writer io.Writer) error {
scanner := bufio.NewScanner(reader)
bufWriter := bufio.NewWriter(writer)
defer bufWriter.Flush()
var processNext bool
var testCases []TestCase
var cur string
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if containsAny(line, inputPrefixes) {
tmp := processRawLine(line)
if *companion {
testCases = append(testCases, TestCase{Test: tmp})
} else {
writer.Write([]byte(tmp))
}
processNext = false // Reset the flag after processing input
} else if processNext {
cur += processRawLine(line)
processNext = false
} else if strings.HasSuffix(line, "=") {
// If the line ends with '=', it indicates the start of a new input section
processNext = true
} else if line == "----" {
if *companion {
testCases = append(testCases, TestCase{Test: cur})
} else {
writer.Write([]byte(cur))
}
cur = ""
}
}
if len(cur) > 0 {
if *companion {
testCases = append(testCases, TestCase{Test: cur})
} else {
writer.Write([]byte(cur))
}
}
if *companion && len(testCases) > 0 {
jsonData, err := json.MarshalIndent(testCases, "", " ")
if err != nil {
return err
}
writer.Write(jsonData)
}
return scanner.Err()
}
func logf(format string, args ...interface{}) {
if *verbose {
log.Printf(format, args...)
}
}
func validateFlags() error {
if *inputFile == "" {
return fmt.Errorf("input file must be specified")
}
if _, err := os.Stat(*inputFile); os.IsNotExist(err) {
return fmt.Errorf("input file does not exist: %s", *inputFile)
}
return nil
}
func containsAny(s string, substrs []string) bool {
for _, substr := range substrs {
if strings.Contains(s, substr) {
return true
}
}
return false
}
func backupFile(fileName string) error {
if len(fileName) == 0 {
return nil
}
// If a suffix name is provided, copy the output file to "input_<suffix>.txt"
newName := fmt.Sprintf("input_%s.txt", fileName)
newFile, err := os.Create(newName)
if err != nil {
return err
}
defer newFile.Close()
readFh, err := os.Open(DefaultOutputFile)
if err != nil {
return err
}
defer readFh.Close()
_, err = io.Copy(bufio.NewWriter(newFile), readFh)
if err != nil {
return err
}
return err
}
var trimPrefixes = []string{"输入:", "输入:", "Input:", "Input: ", "input:", "input: "}
func trimPrefixInput(s string) string {
for _, prefix := range trimPrefixes {
s = strings.TrimPrefix(s, prefix)
}
return strings.TrimSpace(s)
}
func processRawLine(line string) string {
parts := getTokens(line)
var sb strings.Builder
for _, line := range parts {
if is2DSlice(line) {
s := rawStrTo2DStrSlice(line)
tmp := twoDimSliceToStr(s)
sb.WriteString(tmp)
} else if is1DSlice(line) {
s := rawStrTo1DStrSlice(line)
tmp := oneDimSliceToStr(s)
sb.WriteString(tmp)
} else {
sb.WriteString(line + "\n")
}
}
return sb.String()
}
func is1DSlice(s string) bool {
return strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") && !is2DSlice(s)
}
func getTokens(line string) []string {
line = trimPrefixInput(line)
line = strings.TrimSpace(line)
if len(line) == 0 {
return nil
}
return doGetTokens(line)
}
func twoDimSliceToStr(slice [][]string) string {
var sb strings.Builder
n := len(slice)
m := len(slice[0])
sb.WriteString(fmt.Sprintf("%d %d\n", n, m))
for _, innerSlice := range slice {
for i, v := range innerSlice {
sb.WriteString(v)
if i < m-1 {
sb.WriteByte(' ')
} else {
sb.WriteByte('\n')
}
}
}
return sb.String()
}
func oneDimSliceToStr(slice []string) string {
var sb strings.Builder
n := len(slice)
sb.WriteString(fmt.Sprintf("%d\n", n))
for i, s := range slice {
sb.WriteString(s)
if i < n-1 {
sb.WriteByte(' ')
} else {
sb.WriteByte('\n')
}
}
return sb.String()
}
// Given a string. Check Whether it is 1-dimensional or 2-dimensional slice
func is2DSlice(s string) bool {
// Check if the string contains multiple inner slices
return strings.Contains(s, "],[") || strings.Contains(s, "], [") || (strings.HasPrefix(s, "[[") && strings.HasSuffix(s, "]]"))
}