|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "encoding/csv" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "log" |
| 10 | + "os" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +// Quiz is structure for questions and answers |
| 16 | +type Quiz struct { |
| 17 | + question, answer string |
| 18 | +} |
| 19 | + |
| 20 | +// Stat is struct for quiz statistics |
| 21 | +type Stat struct { |
| 22 | + all, correct, incorrect int |
| 23 | +} |
| 24 | + |
| 25 | +func readCSV(file string) ([]Quiz, error) { |
| 26 | + f, err := os.Open(file) |
| 27 | + if err != nil { |
| 28 | + return nil, err |
| 29 | + } |
| 30 | + defer f.Close() |
| 31 | + var quizes []Quiz |
| 32 | + r := csv.NewReader(f) |
| 33 | + for { |
| 34 | + line, err := r.Read() |
| 35 | + if err == io.EOF { |
| 36 | + break |
| 37 | + } |
| 38 | + if err != nil { |
| 39 | + return nil, err |
| 40 | + } |
| 41 | + quizes = append(quizes, Quiz{ |
| 42 | + strings.TrimSpace(line[0]), |
| 43 | + strings.TrimSpace(line[1]), |
| 44 | + }) |
| 45 | + } |
| 46 | + return quizes, nil |
| 47 | +} |
| 48 | + |
| 49 | +func quiz(records []Quiz, timeout int) (*Stat, error) { |
| 50 | + var stat Stat |
| 51 | + reader := bufio.NewReader(os.Stdin) |
| 52 | + |
| 53 | + timer := time.NewTimer(time.Second * time.Duration(timeout)) |
| 54 | + errs := make(chan error) |
| 55 | + |
| 56 | + go func() { |
| 57 | + for _, quiz := range records { |
| 58 | + fmt.Print(quiz.question, ":") |
| 59 | + |
| 60 | + ans, err := reader.ReadString('\n') |
| 61 | + if err != nil { |
| 62 | + errs <- err |
| 63 | + } |
| 64 | + stat.all++ |
| 65 | + if strings.TrimRight(ans, "\r\n") == quiz.answer { |
| 66 | + stat.correct++ |
| 67 | + } else { |
| 68 | + stat.incorrect++ |
| 69 | + } |
| 70 | + } |
| 71 | + }() |
| 72 | + |
| 73 | + select { |
| 74 | + case <-errs: |
| 75 | + return nil, <-errs |
| 76 | + case <-timer.C: |
| 77 | + fmt.Println("\ntime's up!") |
| 78 | + } |
| 79 | + |
| 80 | + return &stat, nil |
| 81 | +} |
| 82 | + |
| 83 | +func main() { |
| 84 | + f := flag.String("f", "problems.csv", "input file in csv format") |
| 85 | + t := flag.Int("t", 30, "timeout for the quiz, in seconds") |
| 86 | + flag.Parse() |
| 87 | + recs, err := readCSV(*f) |
| 88 | + if err != nil { |
| 89 | + log.Fatal(err) |
| 90 | + } |
| 91 | + stat, err := quiz(recs, *t) |
| 92 | + if err != nil { |
| 93 | + log.Fatal(err) |
| 94 | + } |
| 95 | + fmt.Printf("\nQuestion answered: %v, Correct: %v, Incorrect: %v\n", stat.all, stat.correct, stat.incorrect) |
| 96 | +} |
0 commit comments