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,40 @@
package quiz
import (
"fmt"
"io"
"github.com/gophercises/quiz/students/hackeryarn/problem"
)
// Quiz represents the quiz to be given to the user
type Quiz struct {
problems []problem.Problem
rightAnswers int
}
// Run runs the quiz for all the problems keeping track of correct answers
func (q *Quiz) Run(w io.Writer, r io.Reader) {
for _, problem := range q.problems {
problem.AskQuestion(w)
correct := problem.CheckAnswer(r)
if correct {
q.rightAnswers++
}
}
q.PrintResults(w)
}
// PrintResults outputs the results of the quiz
func (q Quiz) PrintResults(w io.Writer) {
fmt.Fprintf(w, "You got %d questions right!\n", q.rightAnswers)
}
// New creates a new quiz from the supplied slice of problems
func New(problems []problem.Problem) Quiz {
return Quiz{
problems: problems,
rightAnswers: 0,
}
}

View File

@@ -0,0 +1,66 @@
package quiz
import (
"bytes"
"io"
"reflect"
"strings"
"testing"
"github.com/gophercises/quiz/students/hackeryarn/problem"
)
func TestNew(t *testing.T) {
problems := sampleProblems()
want := Quiz{problems: problems, rightAnswers: 0}
got := New(problems)
if !reflect.DeepEqual(want, got) {
t.Errorf("expeted to create quiz %v got %v", want, got)
}
}
func TestRun(t *testing.T) {
t.Run("it runs the quiz", func(t *testing.T) {
buffer := &bytes.Buffer{}
quiz := createQuiz()
runQuiz(buffer, &quiz)
expectedResults := 2
results := quiz.rightAnswers
if expectedResults != results {
t.Errorf("expected right answers of %v, got %v",
expectedResults, results)
}
expectedOutput := "7+3: 1+1: You got 2 questions right!\n"
if buffer.String() != expectedOutput {
t.Errorf("expected full output %v, got %v",
expectedOutput, buffer)
}
})
}
func sampleProblems() []problem.Problem {
record1 := []string{"7+3", "10"}
record2 := []string{"1+1", "2"}
return []problem.Problem{
problem.New(record1),
problem.New(record2),
}
}
func createQuiz() Quiz {
problems := sampleProblems()
return New(problems)
}
func runQuiz(buffer io.Writer, quiz *Quiz) {
answers := strings.NewReader("10\n2\n")
quiz.Run(buffer, answers)
}