|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/csv" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | +) |
| 9 | + |
| 10 | +type quiz struct { |
| 11 | + total int |
| 12 | + correct int |
| 13 | + incorrect int |
| 14 | + items []*item |
| 15 | +} |
| 16 | +type item struct { |
| 17 | + question string |
| 18 | + answer string |
| 19 | + got string |
| 20 | + correct bool |
| 21 | +} |
| 22 | + |
| 23 | +func main() { |
| 24 | + file := flag.String("file", "problems.csv", "file to parse the quiz") |
| 25 | + flag.Parse() |
| 26 | + qz, err := load(*file) |
| 27 | + if err != nil { |
| 28 | + fmt.Println(err.Error()) |
| 29 | + return |
| 30 | + } |
| 31 | + start(qz) |
| 32 | + score(qz) |
| 33 | + |
| 34 | +} |
| 35 | + |
| 36 | +// load loads the values of the file and return a new quiz |
| 37 | +func load(file string) (*quiz, error) { |
| 38 | + f, err := os.OpenFile(file, os.O_RDONLY, 0666) |
| 39 | + if err != nil { |
| 40 | + return nil, err |
| 41 | + } |
| 42 | + defer f.Close() |
| 43 | + |
| 44 | + r := csv.NewReader(f) |
| 45 | + all, err := r.ReadAll() |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + qz := new(quiz) |
| 50 | + qz.total = len(all) |
| 51 | + |
| 52 | + for _, items := range all { |
| 53 | + i := item{question: items[0], answer: items[1]} |
| 54 | + qz.items = append(qz.items, &i) |
| 55 | + } |
| 56 | + return qz, nil |
| 57 | +} |
| 58 | + |
| 59 | +// score prints the quiz score |
| 60 | +func score(qz *quiz) { |
| 61 | + fmt.Printf("total: %v correct: %v incorrect: %v\n", qz.total, qz.correct, qz.incorrect) |
| 62 | + fmt.Println("Incorrect questions") |
| 63 | + for _, q := range qz.items { |
| 64 | + if !q.correct { |
| 65 | + fmt.Printf("%v answer: %v got: %v\n", q.question, q.answer, q.got) |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +// start starts the quiz |
| 71 | +func start(qz *quiz) { |
| 72 | + fmt.Printf("interactive mode (%v questions in quiz)\n", qz.total) |
| 73 | + for i, item := range qz.items { |
| 74 | + var op = "" |
| 75 | + fmt.Printf("%v) %v?: ", i+1, item.question) |
| 76 | + fmt.Scanln(&op) |
| 77 | + item.got = op |
| 78 | + if op == item.answer { |
| 79 | + qz.correct++ |
| 80 | + item.correct = true |
| 81 | + continue |
| 82 | + } |
| 83 | + qz.incorrect++ |
| 84 | + } |
| 85 | +} |
0 commit comments