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

solution by Soumil-Bhattacharya #131

Open
wants to merge 4 commits 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module gophercises/quiz

go 1.21.6
105 changes: 105 additions & 0 deletions students/Soumil-Bhattacharya/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package main

import (
"encoding/csv"
"flag"
"fmt"
"math/rand"
"os"
"strings"
"time"
)

type problem struct {
q string
a string
}

// Fisher-Yates shuffle algorithm
func Shuffle(data []problem) {
random := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < len(data); i++ {
r := random.Intn(i + 1)
data[i], data[r] = data[r], data[i]
}
}

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

func parseLines(lines [][]string) []problem {
res := make([]problem, len(lines))

for i, line := range lines {
res[i] = problem{
q: line[0],
a: strings.TrimSpace(line[1]),
}
}

return res
}

func main() {
csvFileName := flag.String(
"csv",
"problems.csv",
"a csv file in the format of 'question, answer'",
)
timeLimit := flag.Int("limit", 30, "the time limit for the quiz in seconds")

shuffle := flag.Bool("shuffle", false, "shuffle order of the questions")
flag.Parse()

file, err := os.Open(*csvFileName)
if err != nil {
exit(fmt.Sprintf("Failed to open the CSV file: %s\n", *csvFileName))
}

r := csv.NewReader(file)

lines, err := r.ReadAll()
if err != nil {
exit("Failed to parse the CSV file.")
}
problems := parseLines(lines)

if *shuffle {
Shuffle(problems)
}

timer := time.NewTimer(time.Duration(*timeLimit) * time.Second)

correct := 0
problemLoop:
for index, problem := range problems {

fmt.Printf("Problem #%d: %s = ", index+1, problem.q)
answerCh := make(chan string)

go func() {
var answer string
fmt.Scanf("%s\n", &answer)
answer = strings.TrimSpace(answer)
answer = strings.ToUpper(answer)
answerCh <- answer
}()
select {
case <-timer.C:
fmt.Println()
break problemLoop
case answer := <-answerCh:

if problem.a == answer {
correct++
}

}

}
// <-timer.C

fmt.Printf("\nYou scored %d out of %d", correct, len(problems))
}
12 changes: 12 additions & 0 deletions students/Soumil-Bhattacharya/problems.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
5+5,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