|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "encoding/csv" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "log" |
| 10 | + "os" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +func fatalError(message string, err error) { |
| 15 | + if err != nil { |
| 16 | + log.Fatalln(message, ":", err) |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +type question struct { |
| 21 | + question string |
| 22 | + answer string |
| 23 | +} |
| 24 | + |
| 25 | +type quiz struct { |
| 26 | + answered int |
| 27 | + answeredCorrectly int |
| 28 | + questions []question |
| 29 | +} |
| 30 | + |
| 31 | +// loadQuiz loads all questions into memory, assumed to be safe as |
| 32 | +// the instructions state that the quiz will be < 100 questions |
| 33 | +func loadQuiz(filePath string) *quiz { |
| 34 | + csvFile, err := os.Open(filePath) |
| 35 | + fatalError("Error opening quiz CSV file", err) |
| 36 | + defer csvFile.Close() |
| 37 | + reader := csv.NewReader(bufio.NewReader(csvFile)) |
| 38 | + var quiz quiz |
| 39 | + for { |
| 40 | + line, err := reader.Read() |
| 41 | + if err == io.EOF { |
| 42 | + break |
| 43 | + } |
| 44 | + fatalError("Error parsing CSV", err) |
| 45 | + question := question{line[0], line[1]} |
| 46 | + quiz.questions = append(quiz.questions, question) |
| 47 | + } |
| 48 | + return &quiz |
| 49 | +} |
| 50 | + |
| 51 | +// run prints questions, check answers, and records total |
| 52 | +// answered and total correct |
| 53 | +func (quiz *quiz) run() { |
| 54 | + timer := time.NewTimer(time.Duration(*timeLimit) * time.Second) |
| 55 | +quizLoop: |
| 56 | + for _, question := range quiz.questions { |
| 57 | + fmt.Println(question.question) |
| 58 | + answerCh := make(chan string) |
| 59 | + go func() { |
| 60 | + scanner.Scan() |
| 61 | + answer := scanner.Text() |
| 62 | + answerCh <- answer |
| 63 | + }() |
| 64 | + select { |
| 65 | + case <-timer.C: |
| 66 | + break quizLoop |
| 67 | + case answer := <-answerCh: |
| 68 | + if answer == question.answer { |
| 69 | + quiz.answeredCorrectly++ |
| 70 | + } |
| 71 | + quiz.answered++ |
| 72 | + } |
| 73 | + } |
| 74 | + return |
| 75 | +} |
| 76 | + |
| 77 | +// report prints summary of quiz performance |
| 78 | +func (quiz *quiz) report() { |
| 79 | + fmt.Printf( |
| 80 | + "You answered %v questions out of a total of %v and got %v correct", |
| 81 | + quiz.answered, |
| 82 | + len(quiz.questions), |
| 83 | + quiz.answeredCorrectly, |
| 84 | + ) |
| 85 | +} |
| 86 | + |
| 87 | +var ( |
| 88 | + scanner = bufio.NewScanner(os.Stdin) |
| 89 | + filePathPtr = flag.String("file", "./problems.csv", "Path to csv file containing quiz.") |
| 90 | + timeLimit = flag.Int64("time-limit", 30, "Set the total time in seconds allowed for the quiz.") |
| 91 | +) |
| 92 | + |
| 93 | +func main() { |
| 94 | + quiz := loadQuiz(*filePathPtr) |
| 95 | + quiz.run() |
| 96 | + quiz.report() |
| 97 | +} |
0 commit comments