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,49 @@
package problem
import (
"fmt"
"io"
"log"
"strings"
)
// Problem represents a single question answer pair
type Problem struct {
question string
answer string
}
// CheckAnswer checks the answer against the provided input
func (p Problem) CheckAnswer(r io.Reader) bool {
answer := readAnswer(r)
if answer != p.answer {
return false
}
return true
}
func readAnswer(r io.Reader) (answer string) {
_, err := fmt.Fscanln(r, &answer)
if err != nil {
log.Fatalln("Error reading in answer", err)
}
return strings.TrimSpace(answer)
}
// AskQuestion prints out the question
func (p Problem) AskQuestion(w io.Writer) {
_, err := fmt.Fprintf(w, "%s: ", p.question)
if err != nil {
log.Fatalln("Could not ask the question", err)
}
}
// New creates a Problem from a provided CSV record
func New(record []string) Problem {
return Problem{
question: record[0],
answer: record[1],
}
}

View File

@@ -0,0 +1,68 @@
package problem
import (
"bytes"
"testing"
)
func TestNew(t *testing.T) {
record := []string{"question", "answer"}
want := Problem{"question", "answer"}
got := New(record)
if got != want {
t.Errorf("expected to create problem %v got %v", want, got)
}
}
func TestCheckAnswer(t *testing.T) {
problem := createProblem()
t.Run("it checks the correct answer", func(t *testing.T) {
answer := getAnswer(problem, "10\n")
checkAnswer(t, answer, true)
})
t.Run("it checks incorrect answer", func(t *testing.T) {
answer := getAnswer(problem, "2\n")
checkAnswer(t, answer, false)
})
}
func TestAskQuestion(t *testing.T) {
problem := createProblem()
t.Run("it asks the question", func(t *testing.T) {
buffer := bytes.NewBuffer(nil)
problem.AskQuestion(buffer)
want := "7+3: "
got := buffer.String()
if want != got {
t.Errorf("Expected question %s, got %s", want, got)
}
})
}
func createProblem() Problem {
record := []string{"7+3", "10"}
return New(record)
}
func getAnswer(problem Problem, input string) bool {
r := bytes.NewBufferString(input)
return problem.CheckAnswer(r)
}
func checkAnswer(t *testing.T, got, want bool) {
if want != got {
t.Errorf("Expected to return %v got %v", want, got)
}
}