|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/csv" |
| 5 | + "os" |
| 6 | + "fmt" |
| 7 | + "strings" |
| 8 | + "log" |
| 9 | + "flag" |
| 10 | + "time" |
| 11 | + "math/rand" |
| 12 | +) |
| 13 | + |
| 14 | +type Question struct { |
| 15 | + question string |
| 16 | + answer string |
| 17 | +} |
| 18 | + |
| 19 | +func getQuestions(filePath string) ([]Question) { |
| 20 | + file, err := os.Open(filePath) |
| 21 | + if(err != nil){ |
| 22 | + log.Fatal("Failed to open file.") |
| 23 | + } |
| 24 | + reader := csv.NewReader(file) |
| 25 | + questionList, err := reader.ReadAll() |
| 26 | + if(err != nil) { |
| 27 | + log.Fatal("Failed to parse CSV file.") |
| 28 | + } |
| 29 | + questions := make([]Question, 0) |
| 30 | + |
| 31 | + for _, question := range questionList { |
| 32 | + questions = append(questions, Question{strings.TrimSpace(question[0]), |
| 33 | + strings.TrimSpace(question[1])}) |
| 34 | + } |
| 35 | + return questions |
| 36 | +} |
| 37 | + |
| 38 | +func Quiz(questions []Question, timer *time.Timer) (score int){ |
| 39 | + |
| 40 | + for i, question := range questions { |
| 41 | + fmt.Printf("Problem #%d %s : ", i + 1, question.question) |
| 42 | + answerChannel := make(chan string) |
| 43 | + go func() { |
| 44 | + var userAnswer string |
| 45 | + fmt.Scanln(&userAnswer) |
| 46 | + answerChannel <- userAnswer |
| 47 | + }() |
| 48 | + |
| 49 | + select { |
| 50 | + case <-timer.C: |
| 51 | + fmt.Println("\nTimeout") |
| 52 | + return score |
| 53 | + case userAnswer := <- answerChannel: |
| 54 | + if(strings.TrimSpace(userAnswer) == question.answer) { |
| 55 | + score += 1 |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + return score |
| 60 | +} |
| 61 | + |
| 62 | +func randomize(questions []Question) []Question{ |
| 63 | + n := len(questions) |
| 64 | + for i := n-1; i>0; i-- { |
| 65 | + j := rand.Intn(i) |
| 66 | + temp := questions[i] |
| 67 | + questions[i] = questions[j] |
| 68 | + questions[j] = temp |
| 69 | + } |
| 70 | + return questions |
| 71 | +} |
| 72 | + |
| 73 | +var csvPath string |
| 74 | +var timeout int |
| 75 | +var shuffle bool |
| 76 | + |
| 77 | +func init() { |
| 78 | + flag.StringVar(&csvPath, "csv", "problems.csv", "a CSV file in format of 'question,answer'") |
| 79 | + flag.IntVar(&timeout, "limit", 30, "The time limit of the quiz in seconds") |
| 80 | + flag.BoolVar(&shuffle, "shuffle", false, "Shuffle the questions (default 'false')") |
| 81 | +} |
| 82 | + |
| 83 | +func main() { |
| 84 | + flag.Parse() |
| 85 | + fmt.Print("Hit Enter to start the timer:") |
| 86 | + questions := getQuestions(csvPath) |
| 87 | + if(shuffle) { |
| 88 | + questions = randomize(questions) |
| 89 | + } |
| 90 | + fmt.Scanln() |
| 91 | + timer := time.NewTimer(time.Second * time.Duration(timeout)) |
| 92 | + score := Quiz(questions, timer) |
| 93 | + fmt.Printf("Your scored %d out of %d\n", score, len(questions)) |
| 94 | +} |
0 commit comments