Skip to content

Commit 97ea734

Browse files
kdlugjoncalhoun
authored andcommitted
Quiz excercise (#35)
1 parent 024f75b commit 97ea734

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed

students/kdlug/main.go

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"bytes"
6+
"encoding/csv"
7+
"flag"
8+
"fmt"
9+
"io/ioutil"
10+
"log"
11+
"math/rand"
12+
"os"
13+
"strings"
14+
"time"
15+
)
16+
17+
func main() {
18+
csvFile := flag.String("csv", "problems.csv", "csv file with questions and answers")
19+
duration := flag.Int("time", 30, "quiz time limit")
20+
randomize := flag.Bool("random", false, "randomize questions")
21+
22+
// Parse
23+
flag.Parse()
24+
25+
reader := bufio.NewReader(os.Stdin)
26+
questions := loadRecordsFromCsv(*csvFile)
27+
correct := 0
28+
total := len(questions) - 1
29+
30+
if *randomize {
31+
questions = shuffle(questions)
32+
}
33+
34+
fmt.Println("Total Questions:", total)
35+
fmt.Println("Duration [s]:", *duration)
36+
37+
done := make(chan bool, 1)
38+
39+
go func() {
40+
for i := 0; i < total; i++ {
41+
fmt.Printf("Question #%d %s = ", i+1, questions[i][0])
42+
43+
answer, _ := reader.ReadString('\n')
44+
// convert CRLF to LF
45+
answer = strings.Replace(answer, "\n", "", -1)
46+
answer = strings.ToLower(answer)
47+
answer = strings.TrimSpace(answer)
48+
49+
// compare answer
50+
if strings.Compare(questions[i][1], answer) == 0 {
51+
correct++
52+
}
53+
54+
}
55+
done <- true
56+
}()
57+
58+
select {
59+
case <-done:
60+
fmt.Println("Good Job!")
61+
62+
case <-time.After(time.Duration(*duration) * time.Second):
63+
fmt.Println("\nYou reached maximum time.")
64+
}
65+
66+
fmt.Println("Your score:", correct, "/", total)
67+
}
68+
69+
// shuffle questions
70+
func shuffle(questions [][]string) [][]string {
71+
s := rand.NewSource(time.Now().UnixNano())
72+
r := rand.New(s)
73+
74+
for i := range questions {
75+
np := r.Intn(len(questions) - 1)
76+
questions[i], questions[np] = questions[np], questions[i]
77+
}
78+
79+
return questions
80+
}
81+
82+
func loadRecordsFromCsv(csvFile string) [][]string {
83+
84+
// load csv file into memory, returns bytes
85+
content, err := ioutil.ReadFile(csvFile)
86+
if err != nil {
87+
log.Fatal(err)
88+
}
89+
90+
r := csv.NewReader(bytes.NewReader(content)) // if we have string instead of btes we can use strings.NewReader(content)
91+
92+
records, err := r.ReadAll()
93+
94+
if err != nil {
95+
log.Fatal(err)
96+
}
97+
98+
return records[1:len(records)]
99+
}

students/kdlug/problems.csv

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
question,answer
2+
5+5,10
3+
7+3,10
4+
1+1,2
5+
8+3,11
6+
1+2,3
7+
8+6,14
8+
3+1,4
9+
1+4,5
10+
5+1,6
11+
2+3,5
12+
3+3,6
13+
2+4,6
14+
5+2,7

0 commit comments

Comments
 (0)