Skip to content

Commit 34c3115

Browse files
ehernandez-xkjoncalhoun
authored andcommitted
quiz part 1 (#17)
1 parent 92549a1 commit 34c3115

File tree

3 files changed

+102
-0
lines changed

3 files changed

+102
-0
lines changed

students/ehernandez/main.go

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package main
2+
3+
import (
4+
"encoding/csv"
5+
"flag"
6+
"fmt"
7+
"os"
8+
)
9+
10+
type quiz struct {
11+
total int
12+
correct int
13+
incorrect int
14+
items []*item
15+
}
16+
type item struct {
17+
question string
18+
answer string
19+
got string
20+
correct bool
21+
}
22+
23+
func main() {
24+
file := flag.String("file", "problems.csv", "file to parse the quiz")
25+
flag.Parse()
26+
qz, err := load(*file)
27+
if err != nil {
28+
fmt.Println(err.Error())
29+
return
30+
}
31+
start(qz)
32+
score(qz)
33+
34+
}
35+
36+
// load loads the values of the file and return a new quiz
37+
func load(file string) (*quiz, error) {
38+
f, err := os.OpenFile(file, os.O_RDONLY, 0666)
39+
if err != nil {
40+
return nil, err
41+
}
42+
defer f.Close()
43+
44+
r := csv.NewReader(f)
45+
all, err := r.ReadAll()
46+
if err != nil {
47+
return nil, err
48+
}
49+
qz := new(quiz)
50+
qz.total = len(all)
51+
52+
for _, items := range all {
53+
i := item{question: items[0], answer: items[1]}
54+
qz.items = append(qz.items, &i)
55+
}
56+
return qz, nil
57+
}
58+
59+
// score prints the quiz score
60+
func score(qz *quiz) {
61+
fmt.Printf("total: %v correct: %v incorrect: %v\n", qz.total, qz.correct, qz.incorrect)
62+
fmt.Println("Incorrect questions")
63+
for _, q := range qz.items {
64+
if !q.correct {
65+
fmt.Printf("%v answer: %v got: %v\n", q.question, q.answer, q.got)
66+
}
67+
}
68+
}
69+
70+
// start starts the quiz
71+
func start(qz *quiz) {
72+
fmt.Printf("interactive mode (%v questions in quiz)\n", qz.total)
73+
for i, item := range qz.items {
74+
var op = ""
75+
fmt.Printf("%v) %v?: ", i+1, item.question)
76+
fmt.Scanln(&op)
77+
item.got = op
78+
if op == item.answer {
79+
qz.correct++
80+
item.correct = true
81+
continue
82+
}
83+
qz.incorrect++
84+
}
85+
}

students/ehernandez/p2.csv

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2x2,4
2+
5x6,30
3+
8x2,16
4+
9x6,54

students/ehernandez/problems.csv

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

0 commit comments

Comments
 (0)