forked from gophercises/quiz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquiz.go
79 lines (67 loc) · 1.41 KB
/
quiz.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
package main
import (
"bufio"
"encoding/csv"
"fmt"
"os"
"strings"
"time"
)
func main() {
timer := time.NewTimer(360 * time.Second)
records := getQuestions()
answersChannel := make(chan int)
done := make(chan bool)
go quizLoop(records, answersChannel, done)
total := 0
for {
select {
case a := <-answersChannel:
total += a
case <-timer.C:
fmt.Println(
"Times up!",
fmt.Sprintf("\nYour score: %v/%v", total, len(records)),
)
return
case <-done:
fmt.Println(
"Nice, you answered all questions!",
fmt.Sprintf("\nYour score: %v/%v", total, len(records)),
)
return
}
}
}
func quizLoop(records [][]string, answersChannel chan int, done chan bool) {
for _, record := range records {
question, answer := record[0], record[1]
fmt.Print(question, "= ")
answersChannel <- checkAnswer(answer)
}
done <- true
}
func getQuestions() [][]string {
file, er := os.Open("problems.csv")
logAndExitIfError(er)
reader := csv.NewReader(file)
records, er := reader.ReadAll()
logAndExitIfError(er)
return records
}
// Returns 1 when correct answer, 0 otherwise.
func checkAnswer(answer string) int {
reader := bufio.NewReader(os.Stdin)
providedAnswer, er := reader.ReadString('\n')
logAndExitIfError(er)
if strings.Trim(providedAnswer, "\n") == answer {
return 1
}
return 0
}
func logAndExitIfError(er error) {
if er != nil {
fmt.Println("Error", er)
os.Exit(1)
}
}