-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (66 loc) · 1.58 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
package main
import (
"encoding/csv"
"flag"
"fmt"
"os"
"time"
)
type Problem struct {
question string
answer string
}
func main() {
filename, timerDuration := readArguments()
file, err := os.Open(filename)
if err != nil {
panic("Failed to open " + filename + " file")
}
defer file.Close()
reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
panic("Failed to read " + filename + " file")
}
problems := parseRecords(records)
correctAnswers := 0
timer := time.NewTimer(time.Duration(timerDuration) * time.Second)
for i, problem := range problems {
fmt.Printf("Problem #%d: %s=", i+1, problem.question)
answerCh := make(chan string)
go scanAnswer(answerCh)
select {
case <-timer.C:
fmt.Printf("\nYour time is expired. You scored %d out of %d.", correctAnswers, len(problems))
return
case answer := <-answerCh:
if answer == problem.answer {
correctAnswers += 1
}
}
}
fmt.Printf("You scored %d out of %d.", correctAnswers, len(problems))
}
func readArguments() (string, int) {
filename := flag.String("filename", "problems.csv", "CSV filename")
timerDuration := flag.Int("time", 30, "Timer duration in seconds")
flag.Parse()
return *filename, *timerDuration
}
func parseRecords(records [][]string) []Problem {
problems := make([]Problem, len(records))
for i, record := range records {
problems[i] = Problem{
question: record[0],
answer: record[1],
}
}
return problems
}
func scanAnswer(ch chan string) {
answer := ""
if _, err := fmt.Scanln(&answer); err != nil {
answer = ""
}
ch <- answer
}