Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: Math quiz algorithm #1205

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions Math quiz/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package main

import (
"encoding/csv"
"flag"
"fmt"
"os"
"time"
)

func main() {
fileName := flag.String("f", "quiz.csv", "path of the file")
timer := flag.Int("t", 30, "timer for the quiz")
flag.Parse()
questionAndAnswer,err := pullQuestion(*fileName)
if err != nil{
exit(fmt.Sprintf("Something went wrong, try again later: %w, file: %s", err, fileName))
}
correctAnswer := 0
tObj := time.NewTimer(time.Duration(*timer)*time.Second)
ansC := make(chan string)

problemLoop:
// var answer string
for i,p := range questionAndAnswer{
var answer string
fmt.Println("Q: "+ p.question)

go func() {
fmt.Scanf("%s", &answer)
ansC <- answer
}()
select{
case <-tObj.C:
fmt.Println()
break problemLoop
case iAns := <-ansC:
if iAns == p.answer{
correctAnswer++
}
if i==len(questionAndAnswer)-1{
close(ansC)
}
}
}

fmt.Printf("You scored %d marks out of %d", correctAnswer, len(questionAndAnswer))
fmt.Println("\nPress Enter to exit")
<-ansC
}

func pullQuestion(fileName string)([]questionAndAnswer, error){

if fObj, err := os.Open(fileName); err == nil {
csvR := csv.NewReader(fObj)
if cLines, err := csvR.ReadAll(); err == nil{
return parseQuestion(cLines), nil
} else {
return nil, fmt.Errorf("Error reading the file %s: %w", fileName, err)
}
} else {
return nil, fmt.Errorf("Error opening file %s", fileName);
}


}

type questionAndAnswer struct{
question string
answer string
}

func parseQuestion(allQuestions [][]string) []questionAndAnswer{

r := make ([]questionAndAnswer, len(allQuestions))
for i := 0; i<len(allQuestions); i++{
r[i] = questionAndAnswer{question: allQuestions[i][0], answer: allQuestions[i][1]}
}
return r
}

func exit(msg string){
fmt.Println(msg)
os.Exit(1)
}


// what did I learn -
// how to read a csv file using encoding/csv
5 changes: 5 additions & 0 deletions Math quiz/quiz.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
1221+99,1320
756+36,792
1+1,2
9+189,198
69+96,165