|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "encoding/csv" |
| 7 | + "flag" |
| 8 | + "fmt" |
| 9 | + "io/ioutil" |
| 10 | + "log" |
| 11 | + "math/rand" |
| 12 | + "os" |
| 13 | + "strings" |
| 14 | + "time" |
| 15 | +) |
| 16 | + |
| 17 | +func main() { |
| 18 | + csvFile := flag.String("csv", "problems.csv", "csv file with questions and answers") |
| 19 | + duration := flag.Int("time", 30, "quiz time limit") |
| 20 | + randomize := flag.Bool("random", false, "randomize questions") |
| 21 | + |
| 22 | + // Parse |
| 23 | + flag.Parse() |
| 24 | + |
| 25 | + reader := bufio.NewReader(os.Stdin) |
| 26 | + questions := loadRecordsFromCsv(*csvFile) |
| 27 | + correct := 0 |
| 28 | + total := len(questions) - 1 |
| 29 | + |
| 30 | + if *randomize { |
| 31 | + questions = shuffle(questions) |
| 32 | + } |
| 33 | + |
| 34 | + fmt.Println("Total Questions:", total) |
| 35 | + fmt.Println("Duration [s]:", *duration) |
| 36 | + |
| 37 | + done := make(chan bool, 1) |
| 38 | + |
| 39 | + go func() { |
| 40 | + for i := 0; i < total; i++ { |
| 41 | + fmt.Printf("Question #%d %s = ", i+1, questions[i][0]) |
| 42 | + |
| 43 | + answer, _ := reader.ReadString('\n') |
| 44 | + // convert CRLF to LF |
| 45 | + answer = strings.Replace(answer, "\n", "", -1) |
| 46 | + answer = strings.ToLower(answer) |
| 47 | + answer = strings.TrimSpace(answer) |
| 48 | + |
| 49 | + // compare answer |
| 50 | + if strings.Compare(questions[i][1], answer) == 0 { |
| 51 | + correct++ |
| 52 | + } |
| 53 | + |
| 54 | + } |
| 55 | + done <- true |
| 56 | + }() |
| 57 | + |
| 58 | + select { |
| 59 | + case <-done: |
| 60 | + fmt.Println("Good Job!") |
| 61 | + |
| 62 | + case <-time.After(time.Duration(*duration) * time.Second): |
| 63 | + fmt.Println("\nYou reached maximum time.") |
| 64 | + } |
| 65 | + |
| 66 | + fmt.Println("Your score:", correct, "/", total) |
| 67 | +} |
| 68 | + |
| 69 | +// shuffle questions |
| 70 | +func shuffle(questions [][]string) [][]string { |
| 71 | + s := rand.NewSource(time.Now().UnixNano()) |
| 72 | + r := rand.New(s) |
| 73 | + |
| 74 | + for i := range questions { |
| 75 | + np := r.Intn(len(questions) - 1) |
| 76 | + questions[i], questions[np] = questions[np], questions[i] |
| 77 | + } |
| 78 | + |
| 79 | + return questions |
| 80 | +} |
| 81 | + |
| 82 | +func loadRecordsFromCsv(csvFile string) [][]string { |
| 83 | + |
| 84 | + // load csv file into memory, returns bytes |
| 85 | + content, err := ioutil.ReadFile(csvFile) |
| 86 | + if err != nil { |
| 87 | + log.Fatal(err) |
| 88 | + } |
| 89 | + |
| 90 | + r := csv.NewReader(bytes.NewReader(content)) // if we have string instead of btes we can use strings.NewReader(content) |
| 91 | + |
| 92 | + records, err := r.ReadAll() |
| 93 | + |
| 94 | + if err != nil { |
| 95 | + log.Fatal(err) |
| 96 | + } |
| 97 | + |
| 98 | + return records[1:len(records)] |
| 99 | +} |
0 commit comments