Skip to content

Commit

Permalink
Liikt's solution for the quiz (gophercises#21)
Browse files Browse the repository at this point in the history
* my solution for the quiz

* implemented the suggestions from @arsham
  • Loading branch information
Julian authored and joncalhoun committed Jul 23, 2019
1 parent 8b6e57d commit 82fe91a
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
77 changes: 77 additions & 0 deletions students/liikt/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package main

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

var (
problemsFile string
timeout int
correct int
b bool
inChan chan int
outChan chan int
)

func getAnswer(solution string) {
var inp string
fmt.Scanln(&inp)
if sanitize(inp) == sanitize(solution) {
outChan <- <-inChan + 1
} else {
outChan <- <-inChan
}
}

func updateCorrect() bool {
select {
case res := <-outChan:
correct = res
return true
case <-time.After(time.Duration(timeout) * time.Second):
close(outChan)
fmt.Println()
return false
}
}

func sanitize(s string) string {
return strings.ToLower(strings.Trim(s, "\n\r\t "))
}

func main() {
flag.StringVar(&problemsFile, "path", "problems.csv", "This is the flag to the CSV containing the problems for the quiz")
flag.IntVar(&timeout, "timeout", 30, "The amount of time you have for a single question in seconds")
flag.Parse()

file, err := os.Open(problemsFile)
if err != nil {
log.Fatal(err)
}
defer file.Close()

problems, err := csv.NewReader(file).ReadAll()
if err != nil {
log.Fatal(err)
}

inChan, outChan = make(chan int, 1), make(chan int, 1)
for c, q := range problems {
fmt.Printf("Question %v: %v -> ", c, q[0])

go getAnswer(q[1])
inChan <- correct

if !updateCorrect() {
break
}

}
fmt.Println("You got", correct, "out of", len(problems), "correct.")
}
12 changes: 12 additions & 0 deletions students/liikt/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

0 comments on commit 82fe91a

Please sign in to comment.