|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/csv" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | +) |
| 11 | + |
| 12 | +type problem struct { |
| 13 | + question string |
| 14 | + answer string |
| 15 | + userAnswer string |
| 16 | + isCorrect bool |
| 17 | +} |
| 18 | + |
| 19 | +func main() { |
| 20 | + csvFileName := flag.String("csv", "problems.csv", "A csv file of format 'question,answer'") |
| 21 | + timeLimit := flag.Int("limit", 30, "The time limit of quiz in seconds") |
| 22 | + flag.Parse() |
| 23 | + |
| 24 | + file, err := os.Open(*csvFileName) |
| 25 | + if err != nil { |
| 26 | + exit(fmt.Sprintf("Could not open file %s\n", *csvFileName)) |
| 27 | + } |
| 28 | + r := csv.NewReader(file) |
| 29 | + lines, err := r.ReadAll() |
| 30 | + if err != nil { |
| 31 | + exit("Failed to parse the CSV file") |
| 32 | + } |
| 33 | + problems := parseLines(lines) |
| 34 | + |
| 35 | + timer := time.NewTimer(time.Duration((*timeLimit)) * time.Second) |
| 36 | + start := time.Now() |
| 37 | + |
| 38 | + correctCount := 0 |
| 39 | +problemloop: |
| 40 | + for i := 0; i < len(problems); i++ { |
| 41 | + fmt.Printf("Problem #%d: %s = ", i+1, problems[i].question) |
| 42 | + ansChan := make(chan string) |
| 43 | + go func() { |
| 44 | + var answer string |
| 45 | + fmt.Scanf("%s\n", &answer) |
| 46 | + problems[i].userAnswer = answer |
| 47 | + ansChan <- answer |
| 48 | + }() |
| 49 | + |
| 50 | + select { |
| 51 | + case <-timer.C: |
| 52 | + fmt.Println() |
| 53 | + break problemloop |
| 54 | + case answer := <-ansChan: |
| 55 | + if answer == problems[i].answer { |
| 56 | + problems[i].isCorrect = true |
| 57 | + correctCount++ |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + timer.Stop() |
| 62 | + for i, prob := range problems { |
| 63 | + check := "\u274C" |
| 64 | + if prob.isCorrect { |
| 65 | + check = "\u2705" |
| 66 | + } |
| 67 | + fmt.Printf("Problem #%d: %s = %s %s %s\n", i+1, prob.question, prob.userAnswer, string(check), prob.answer) |
| 68 | + } |
| 69 | + |
| 70 | + fmt.Printf("You scored %d out of %d in time %f seconds.\n", correctCount, len(problems), time.Since(start).Seconds()) |
| 71 | +} |
| 72 | + |
| 73 | +func parseLines(lines [][]string) []problem { |
| 74 | + ret := make([]problem, len(lines)) |
| 75 | + for i, line := range lines { |
| 76 | + ret[i] = problem{ |
| 77 | + question: line[0], |
| 78 | + answer: strings.TrimSpace(line[1]), |
| 79 | + } |
| 80 | + } |
| 81 | + return ret |
| 82 | +} |
| 83 | + |
| 84 | +func exit(msg string) { |
| 85 | + fmt.Println(msg) |
| 86 | + os.Exit(1) |
| 87 | +} |
0 commit comments