-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (65 loc) · 1.32 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
package main
import (
"encoding/csv"
"flag"
"fmt"
"os"
"strings"
"time"
)
type question struct {
q string
a string
}
func main() {
csvFile := flag.String("csv", "problems.csv", "a csv file in the format 'question, answer'")
limit := flag.Int("limit", 30, "time limit to finish the quiz")
flag.Parse()
f, err := os.Open(*csvFile)
if err != nil {
panic(err)
}
defer f.Close()
reader := csv.NewReader(f)
rows, err := reader.ReadAll()
if err != nil {
handleErr(err)
}
questions := parseRows(rows)
timer := time.NewTimer(time.Duration(*limit) * time.Second)
var counter int
loopquestions:
for idx, question := range questions {
fmt.Printf("Problem #%d: %s = ", (idx + 1), question.q)
respch := make(chan string)
go func() {
var resp string
fmt.Scanf("%s\n", &resp)
respch <- resp
}()
select {
case <-timer.C:
fmt.Println()
break loopquestions
case resp := <-respch:
if resp == question.a {
counter++
}
}
}
fmt.Printf("You scored %d out of %d", counter, len(questions))
}
func parseRows(rows [][]string) []question {
questions := make([]question, len(rows))
for i, row := range rows {
questions[i] = question{
q: row[0],
a: strings.TrimSpace(row[1]),
}
}
return questions
}
func handleErr(err error) {
fmt.Errorf("An error occurred %v", err)
os.Exit(1)
}