-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.go
91 lines (71 loc) · 2.07 KB
/
game.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"math"
"math/rand"
)
type GameResult struct {
Win bool
Guesses []Word
}
type Game struct {
Dictionary *Dictionary
FeedbackResolver FeedbackResolver
}
const maxAttempts = 6
// The calculation to determine the optimal first guess is extremely expensive
// and will always produce the same result. Calculating the guess ahead of time
// drastically improves the solver's performance.
var optimalFirstGuess = Word{'s', 'o', 'a', 'r', 'e'}
func (g *Game) Play() (*GameResult, error) {
var (
win bool
guesses []Word
)
g.Dictionary.ResetRemainingPossibleAnswers()
for attempt := 1; attempt <= maxAttempts; attempt++ {
guess := g.guess(attempt)
guesses = append(guesses, guess)
feedback := g.FeedbackResolver.Resolve(guess, attempt)
if feedback.Success() {
win = true
break
}
err := g.Dictionary.UpdateRemainingPossibleAnswers(guess, feedback)
if err != nil {
return nil, err
}
}
return &GameResult{Win: win, Guesses: guesses}, nil
}
func (g *Game) guess(attempt int) Word {
if attempt == 1 {
return optimalFirstGuess
}
// Return a random answer if the probability of it being correct is >= 50%
if len(g.Dictionary.RemainingPossibleAnswers) <= 2 {
n := rand.Intn(len(g.Dictionary.RemainingPossibleAnswers))
return g.Dictionary.RemainingPossibleAnswers[n]
}
var (
maxInformationGain float64
optimalGuess Word
)
for _, guess := range g.Dictionary.ValidGuesses() {
feedbackProbabilities := map[Feedback]float64{}
for _, possibleAnswer := range g.Dictionary.RemainingPossibleAnswers {
feedback := buildFeedback(guess, possibleAnswer)
feedbackProbabilities[feedback] += 1.0 / float64(len(g.Dictionary.RemainingPossibleAnswers))
}
// Calculate the entropy to determine the guess that will yield the most information
var sum float64
for _, probability := range feedbackProbabilities {
sum += probability * math.Log(probability)
}
informationGain := -sum
if informationGain > maxInformationGain {
maxInformationGain = informationGain
optimalGuess = guess
}
}
return optimalGuess
}