mirror of
https://github.com/AmanTahiliani/gophercises.git
synced 2026-08-08 04:06:16 -04:00
Different solution for Gophercise 1
This commit is contained in:
85
1. Quiz Game Sol2/students/ehernandez/main.go
Normal file
85
1. Quiz Game Sol2/students/ehernandez/main.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
type quiz struct {
|
||||
total int
|
||||
correct int
|
||||
incorrect int
|
||||
items []*item
|
||||
}
|
||||
type item struct {
|
||||
question string
|
||||
answer string
|
||||
got string
|
||||
correct bool
|
||||
}
|
||||
|
||||
func main() {
|
||||
file := flag.String("file", "problems.csv", "file to parse the quiz")
|
||||
flag.Parse()
|
||||
qz, err := load(*file)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
return
|
||||
}
|
||||
start(qz)
|
||||
score(qz)
|
||||
|
||||
}
|
||||
|
||||
// load loads the values of the file and return a new quiz
|
||||
func load(file string) (*quiz, error) {
|
||||
f, err := os.OpenFile(file, os.O_RDONLY, 0666)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
r := csv.NewReader(f)
|
||||
all, err := r.ReadAll()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qz := new(quiz)
|
||||
qz.total = len(all)
|
||||
|
||||
for _, items := range all {
|
||||
i := item{question: items[0], answer: items[1]}
|
||||
qz.items = append(qz.items, &i)
|
||||
}
|
||||
return qz, nil
|
||||
}
|
||||
|
||||
// score prints the quiz score
|
||||
func score(qz *quiz) {
|
||||
fmt.Printf("total: %v correct: %v incorrect: %v\n", qz.total, qz.correct, qz.incorrect)
|
||||
fmt.Println("Incorrect questions")
|
||||
for _, q := range qz.items {
|
||||
if !q.correct {
|
||||
fmt.Printf("%v answer: %v got: %v\n", q.question, q.answer, q.got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// start starts the quiz
|
||||
func start(qz *quiz) {
|
||||
fmt.Printf("interactive mode (%v questions in quiz)\n", qz.total)
|
||||
for i, item := range qz.items {
|
||||
var op = ""
|
||||
fmt.Printf("%v) %v?: ", i+1, item.question)
|
||||
fmt.Scanln(&op)
|
||||
item.got = op
|
||||
if op == item.answer {
|
||||
qz.correct++
|
||||
item.correct = true
|
||||
continue
|
||||
}
|
||||
qz.incorrect++
|
||||
}
|
||||
}
|
||||
4
1. Quiz Game Sol2/students/ehernandez/p2.csv
Normal file
4
1. Quiz Game Sol2/students/ehernandez/p2.csv
Normal file
@@ -0,0 +1,4 @@
|
||||
2x2,4
|
||||
5x6,30
|
||||
8x2,16
|
||||
9x6,54
|
||||
|
13
1. Quiz Game Sol2/students/ehernandez/problems.csv
Normal file
13
1. Quiz Game Sol2/students/ehernandez/problems.csv
Normal file
@@ -0,0 +1,13 @@
|
||||
5+5,10
|
||||
7+3,10
|
||||
1+1,2
|
||||
8+3,11
|
||||
1+2,3
|
||||
8+6,14
|
||||
3+1,4
|
||||
1+4,5
|
||||
5+1,6
|
||||
2+3,5
|
||||
3+3,6
|
||||
2+4,6
|
||||
5+2,7
|
||||
|
Reference in New Issue
Block a user