-
Notifications
You must be signed in to change notification settings - Fork 714
/
Copy pathmain.go
105 lines (84 loc) · 1.82 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
package main
import (
"encoding/csv"
"flag"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
type problem struct {
q string
a string
}
// Fisher-Yates shuffle algorithm
func Shuffle(data []problem) {
random := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < len(data); i++ {
r := random.Intn(i + 1)
data[i], data[r] = data[r], data[i]
}
}
func exit(msg string) {
fmt.Println(msg)
os.Exit(1)
}
func parseLines(lines [][]string) []problem {
res := make([]problem, len(lines))
for i, line := range lines {
res[i] = problem{
q: line[0],
a: strings.TrimSpace(line[1]),
}
}
return res
}
func main() {
csvFileName := flag.String(
"csv",
"problems.csv",
"a csv file in the format of 'question, answer'",
)
timeLimit := flag.Int("limit", 30, "the time limit for the quiz in seconds")
shuffle := flag.Bool("shuffle", false, "shuffle order of the questions")
flag.Parse()
file, err := os.Open(*csvFileName)
if err != nil {
exit(fmt.Sprintf("Failed to open the CSV file: %s\n", *csvFileName))
}
r := csv.NewReader(file)
lines, err := r.ReadAll()
if err != nil {
exit("Failed to parse the CSV file.")
}
problems := parseLines(lines)
if *shuffle {
Shuffle(problems)
}
timer := time.NewTimer(time.Duration(*timeLimit) * time.Second)
correct := 0
problemLoop:
for index, problem := range problems {
fmt.Printf("Problem #%d: %s = ", index+1, problem.q)
answerCh := make(chan string)
go func() {
var answer string
fmt.Scanf("%s\n", &answer)
answer = strings.TrimSpace(answer)
answer = strings.ToUpper(answer)
answerCh <- answer
}()
select {
case <-timer.C:
fmt.Println()
break problemLoop
case answer := <-answerCh:
if problem.a == answer {
correct++
}
}
}
// <-timer.C
fmt.Printf("\nYou scored %d out of %d", correct, len(problems))
}