|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/csv" |
| 5 | + "errors" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +type recordtype struct { |
| 14 | + question string |
| 15 | + answer string |
| 16 | +} |
| 17 | + |
| 18 | +// ReadStringWithLimitTime - function read string from reader with time limit |
| 19 | +func ReadStringWithLimitTime(limit int) (string, error) { |
| 20 | + timer := time.NewTimer(time.Duration(limit) * time.Second).C |
| 21 | + doneChan := make(chan bool) |
| 22 | + answer, err := "", error(nil) |
| 23 | + go func() { |
| 24 | + fmt.Scanf("%s\n", &answer) |
| 25 | + doneChan <- true |
| 26 | + }() |
| 27 | + for { |
| 28 | + select { |
| 29 | + case <-timer: |
| 30 | + return "", errors.New("Timer expired") |
| 31 | + case <-doneChan: |
| 32 | + return answer, err |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// ParseLines - parse lines from array of array of string to array of recordtype |
| 38 | +func ParseLines(lines [][]string) []recordtype { |
| 39 | + ret := make([]recordtype, len(lines)) |
| 40 | + for i, line := range lines { |
| 41 | + ret[i] = recordtype{ |
| 42 | + question: line[0], |
| 43 | + answer: strings.TrimSpace(line[1]), |
| 44 | + } |
| 45 | + } |
| 46 | + return ret |
| 47 | +} |
| 48 | + |
| 49 | +func exit(msg string) { |
| 50 | + fmt.Println(msg) |
| 51 | + os.Exit(1) |
| 52 | +} |
| 53 | + |
| 54 | +func main() { |
| 55 | + |
| 56 | + problemFileName := flag.String("csv", "./problems.csv", "a csv file in the format 'quastion,answer'") |
| 57 | + limit := flag.Int("limit", 30, "the time limit for the quiz in seconds") |
| 58 | + flag.Parse() |
| 59 | + |
| 60 | + problemFile, err := os.Open(*problemFileName) |
| 61 | + if err != nil { |
| 62 | + exit(fmt.Sprintf("Failed to open the CSV file: %s\n", *problemFileName)) |
| 63 | + } |
| 64 | + |
| 65 | + defer problemFile.Close() // close CSV file |
| 66 | + |
| 67 | + readerProblem := csv.NewReader(problemFile) |
| 68 | + lines, err := readerProblem.ReadAll() |
| 69 | + if err != nil { |
| 70 | + exit("Failed to parse the provided CSV file.") |
| 71 | + } |
| 72 | + |
| 73 | + problems := ParseLines(lines) |
| 74 | + |
| 75 | + successAnswerCount := 0 |
| 76 | + for i, p := range problems { |
| 77 | + fmt.Printf("Problem #%d: %s=", i+1, p.question) |
| 78 | + |
| 79 | + answer, err := ReadStringWithLimitTime(*limit) |
| 80 | + if err != nil { |
| 81 | + println("Time expire!") |
| 82 | + break |
| 83 | + } |
| 84 | + if strings.ToLower(strings.Trim(answer, "\n ")) == p.answer { |
| 85 | + successAnswerCount++ |
| 86 | + } |
| 87 | + } |
| 88 | + println("You scored", successAnswerCount, "out of", len(problems)) |
| 89 | + |
| 90 | +} |
0 commit comments