-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (66 loc) · 1.52 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
package main
import (
"encoding/csv"
"flag"
"fmt"
"os"
"strings"
"time"
)
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 quiz in seconds")
flag.Parse()
_ = csvFilename
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 provided CSV file")
}
correct := 0
problems := parseLines(lines)
timer := time.NewTimer(time.Duration(*timeLimit) * time.Second)
for i, p := range problems {
fmt.Printf("Problem #%d:%s = ", i+1, p.question)
answerCh := make(chan string)
go func() {
var answer string
fmt.Scanf("%s\n", &answer)
answerCh <- answer
}()
select {
case <-timer.C:
fmt.Printf("\n You Scored %d out of %d.\n", correct, len(problems))
return
case answer := <-answerCh:
if answer == p.answer {
correct++
}
}
}
}
// reading the lines and creating and array of the problem struct
func parseLines(lines [][]string) []problem {
ret := make([]problem, len(lines))
for i, line := range lines {
ret[i] = problem{
question: line[0],
answer: strings.TrimSpace(line[1]),
}
}
return ret
}
// defining a a type to hold the question and answer
type problem struct {
question string
answer string
}
// common function for handling errors
func exit(msg string) {
fmt.Println(msg)
os.Exit(1)
}