Skip to content

Commit

Permalink
Add solution to quiz part gophercises#2 (timer)
Browse files Browse the repository at this point in the history
  • Loading branch information
Szymon Mikitiuk committed Feb 4, 2024
1 parent 16d1cc6 commit b948586
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,14 @@ type Question struct {
}

func main() {
fileName, _, shuffle := parseUserInput()
fileName, timeLimit, shuffle := parseUserInput()
questions := readQuestions(fileName)

if shuffle {
scramble(questions)
}
mainLoop(questions)
fmt.Printf("You scored %d out of %d.\n", correctAnswers, correctAnswers+wrongAnswers)

mainLoop(questions, timeLimit)
}

func parseUserInput() (string, int, bool) {
Expand Down Expand Up @@ -72,16 +73,29 @@ func scramble(data []Question) {
})
}

func mainLoop(data []Question) {
for idx, question := range data {
func mainLoop(questions []Question, timeLimit int) {
timer := time.NewTimer(time.Duration(timeLimit) * time.Second)

for idx, question := range questions {
fmt.Printf("Problem #%d: %s = ", idx+1, question.question)
var answer string
fmt.Scan(&answer)

if answer == question.answer {
correctAnswers++
} else {
wrongAnswers++
answerChannel := make(chan string)
go func() {
var answer string
fmt.Scan(&answer)
answerChannel <- answer
}()

select {
case <-timer.C:
fmt.Printf("\nYou scored %d out of %d.\n", correctAnswers, len(questions))
return
case answer := <-answerChannel:
if answer == question.answer {
correctAnswers++
} else {
wrongAnswers++
}
}
}
}

0 comments on commit b948586

Please sign in to comment.