This commit is contained in:
Love 2024-09-04 23:49:46 +02:00
parent 19e6e8db4f
commit a69e768753

View File

@ -5,7 +5,7 @@
#include <string>
#include <unordered_set>
const string ALPHABET = "abcdefghijklmnopqrstuvwxyz";
const std::string ALPHABET = "abcdefghijklmnopqrstuvwxyz";
const char *const FORMAT_UNDERSCORE = "\033[4m";
const char *const END_FORMATTING = "\033[0m";
@ -57,19 +57,80 @@ std::unordered_set<std::string> readDictionary() {
return set;
}
std::stack<std::string>
wordChain(std::string &w1, std::string &w2,
const std::unordered_set<std::string> &dictionary) {
std::unordered_set<std::string> visited;
std::queue<std::stack<std::string>> queue;
{
std::stack<std::string> first;
first.push(w1);
queue.push(first);
}
visited.insert(w1);
while (!queue.empty()) {
std::stack<std::string> front = queue.front();
queue.pop();
std::string latestWord = front.top();
if (latestWord == w2)
return front;
for (int i = 0; i < latestWord.size(); i++) {
for (char c : ALPHABET) {
std::string nextWord = latestWord;
nextWord[i] = c;
bool isVisited = visited.find(nextWord) != visited.end();
if (isVisited)
continue;
bool isValidWord = dictionary.find(nextWord) != dictionary.end();
if (!isValidWord)
continue;
std::stack<std::string> nextStack = front;
nextStack.push(nextWord);
queue.push(nextStack);
visited.insert(nextWord);
}
}
}
return std::stack<std::string>();
}
int main() {
std::cout << "Welcome to TDDD86 Word Chain.\n"
<< "If you give me two English words, I will transform the\n"
<< "first into the second by changing one letter at a time.\n\n"
<<"Please type two words: ";
<< "Please type two words: ";
std::flush(std::cout);
std::unordered_set<std::string> dictionary = readDictionary();
std::string userInput = input(nullptr);
size_t wordSep = userInput.find(' ');
std::string wordOne = userInput.substr(0, wordSep);
std::string wordTwo = userInput.substr(wordSep + 1);
std::cout << "Chain from " << wordTwo << " to " << wordOne << std::endl;
// std::string wordOne = "lead", wordTwo = "gold";
std::cout << "Chain from " << wordTwo << " to " << wordOne << ':'
<< std::endl;
std::stack<std::string> resolutionWords =
wordChain(wordOne, wordTwo, dictionary);
bool isFirst = true;
if (!resolutionWords.empty()) {
do {
std::string resolutionWord = resolutionWords.top();
resolutionWords.pop();
if (isFirst) {
isFirst = false;
} else {
std::cout << ", ";
}
std::cout << resolutionWord;
} while (!resolutionWords.empty());
} else
std::cout << "Couldn't find any resolution :(";
std::cout << std::endl;
std::cout << "Have a nice day!" << std::endl;
return 0;