-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.cpp
77 lines (63 loc) · 2.04 KB
/
solver.cpp
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
#include "Solver.h"
#include <cmath>
#include <cstdlib>
#include <algorithm>
Solver::Solver(int codeLength, int numColors)
: codeLength(codeLength), numColors(numColors) {
reset();
}
void Solver::generateAllCodes() {
possibleCodes.clear();
std::vector<int> code(codeLength, 0);
for (int i = 0; i < pow(numColors, codeLength); ++i) {
for (int j = 0; j < codeLength; ++j) {
code[j] = (i / (int)pow(numColors, j)) % numColors;
}
possibleCodes.push_back(code);
}
}
void Solver::reset() {
generateAllCodes();
currentGuess = {0, 0, 1, 1}; // Knuth suggests starting with this guess
}
std::vector<int> Solver::makeGuess() {
if (!currentGuess.empty()) {
return currentGuess;
}
// Default to the first possible code as the guess
currentGuess = possibleCodes[0];
return currentGuess;
}
void Solver::receiveFeedback(int correctPosition, int correctColor) {
prunePossibleCodes(correctPosition, correctColor);
if (!possibleCodes.empty()) {
currentGuess = possibleCodes[0];
}
}
int Solver::calculateFeedback(const std::vector<int>& guess, const std::vector<int>& code) {
int correctPosition = 0, correctColor = 0;
std::vector<int> codeCount(numColors, 0), guessCount(numColors, 0);
for (int i = 0; i < codeLength; ++i) {
if (guess[i] == code[i]) {
++correctPosition;
} else {
++codeCount[code[i]];
++guessCount[guess[i]];
}
}
for (int i = 0; i < numColors; ++i) {
correctColor += std::min(codeCount[i], guessCount[i]);
}
return (correctPosition << 4) | correctColor; // Encode feedback as a single value
}
void Solver::prunePossibleCodes(int correctPosition, int correctColor) {
std::vector<std::vector<int>> newPossibleCodes;
for (const auto& code : possibleCodes) {
if (calculateFeedback(currentGuess, code) == (correctPosition << 4 | correctColor)) {
newPossibleCodes.push_back(code);
}
}
possibleCodes = newPossibleCodes;
}
```
---