Different solution for Gophercise 1

This commit is contained in:
2025-05-31 13:14:20 -04:00
parent b22ab92d79
commit 1da6e395bf
56 changed files with 3374 additions and 0 deletions

View 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++
}
}

View File

@@ -0,0 +1,4 @@
2x2,4
5x6,30
8x2,16
9x6,54
1 2x2 4
2 5x6 30
3 8x2 16
4 9x6 54

View 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
1 5+5 10
2 7+3 10
3 1+1 2
4 8+3 11
5 1+2 3
6 8+6 14
7 3+1 4
8 1+4 5
9 5+1 6
10 2+3 5
11 3+3 6
12 2+4 6
13 5+2 7