-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhackerrank.go
More file actions
112 lines (90 loc) · 1.77 KB
/
hackerrank.go
File metadata and controls
112 lines (90 loc) · 1.77 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
package hackerrank
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
// Type TestCase implements ways of interpreting the input and output files and running code over them.
func Max(a int, b int) int {
if a > b {
return a
}
return b
}
func Min(a int, b int) int {
if a < b {
return a
}
return b
}
type Tests []Test
func NewTests(path string) *Tests {
t := Tests(TestsReaders(path))
return &t
}
func (t *Tests) Run(f func(Test)) {
for k, v := range *t {
f(v)
if k < len(*t)-1 {
fmt.Println()
}
}
}
type Test struct {
Name string
In TestReader
Out TestReader
}
func TestsReaders(path string) []Test {
files, err := ioutil.ReadDir(path)
if err != nil {
log.Fatal(err)
}
tests := make([]Test, 0)
for _, file := range files {
inFileName := file.Name()
extension := filepath.Ext(inFileName)
if strings.HasPrefix(inFileName, "input") && extension == ".txt" {
name := strings.TrimPrefix(inFileName, "input")
name = strings.TrimSuffix(name, extension)
inFilePath := filepath.Join(path, inFileName)
outFilePath := filepath.Join(path, "output"+name+extension)
tests = append(tests, Test{
Name: name,
In: TestReader(fileReader(inFilePath)),
Out: TestReader(fileReader(outFilePath)),
})
}
}
return tests
}
func fileReader(filename string) bufio.Reader {
f, err := os.Open(filename)
if err != nil {
log.Fatalln(err)
}
return *bufio.NewReader(f)
}
type TestReader bufio.Reader
func (t *TestReader) NextLine() string {
reader := bufio.Reader(*t)
bytes, err := reader.ReadBytes('\n')
if err != nil {
if err != io.EOF {
log.Fatalln(err)
}
}
s := string(bytes)
if len(s) > 0 {
if rune(s[len(s)-1]) == '\n' {
s = s[:len(s)-1]
}
}
*t = TestReader(reader)
return s
}