Skip to content

Commit 617e1ce

Browse files
hellosputnikjoncalhoun
authored andcommitted
Add hellosputnik's solution (#9)
1 parent 9d49a66 commit 617e1ce

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

students/hellosputnik/main.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"flag"
6+
"fmt"
7+
"os"
8+
"strings"
9+
"time"
10+
)
11+
12+
type Problem struct {
13+
question string
14+
answer string
15+
}
16+
17+
type Quiz struct {
18+
problems []Problem
19+
score int
20+
}
21+
22+
type Settings struct {
23+
filename *string
24+
timeLimit *int
25+
}
26+
27+
func main() {
28+
quiz := Quiz{}
29+
settings := Settings{}
30+
31+
settings.filename = flag.String("csv", "problems.csv", "a csv file in the format of 'question,answer'")
32+
settings.timeLimit = flag.Int("limit", 30, "the time limit for the quiz in seconds")
33+
34+
// Get the flags (if any).
35+
flag.Parse()
36+
37+
// Create a file handle for the file.
38+
file, err := os.Open(*settings.filename)
39+
40+
// If there was an error opening the file, exit.
41+
if err != nil {
42+
panic(err)
43+
}
44+
45+
defer file.Close()
46+
47+
// Create a buffered reader to read the file input.
48+
fin := bufio.NewScanner(file)
49+
50+
// Read the problems from the comma-separated values file.
51+
for fin.Scan() {
52+
line := strings.Split(fin.Text(), ",")
53+
problem := Problem{question: line[0], answer: line[1]}
54+
55+
quiz.problems = append(quiz.problems, problem)
56+
}
57+
58+
// Create a timer to enforce a time limit.
59+
timer := time.NewTimer(time.Second * time.Duration(*settings.timeLimit))
60+
defer timer.Stop()
61+
62+
go func() {
63+
<-timer.C
64+
fmt.Printf("\nYou scored %d out of %d.", quiz.score, len(quiz.problems))
65+
}()
66+
67+
// Quiz the user.
68+
for i, problem := range quiz.problems {
69+
fmt.Printf("Problem #%d: %s = ", (i + 1), problem.question)
70+
71+
var input string
72+
fmt.Scan(&input)
73+
74+
if input == problem.answer {
75+
quiz.score++
76+
}
77+
}
78+
79+
// Print the user's results.
80+
fmt.Printf("You scored %d out of %d.", quiz.score, len(quiz.problems))
81+
}

0 commit comments

Comments
 (0)