From b4df6db4d3cb146e08dc0c7cffb57d9f9a6b1a08 Mon Sep 17 00:00:00 2001 From: Love Billenius Date: Wed, 4 Sep 2024 23:49:46 +0200 Subject: [PATCH] Working! --- src/wordchain.cpp | 67 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 3 deletions(-) diff --git a/src/wordchain.cpp b/src/wordchain.cpp index 5bfa7e9..3fcdce3 100755 --- a/src/wordchain.cpp +++ b/src/wordchain.cpp @@ -5,7 +5,7 @@ #include #include -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 readDictionary() { return set; } +std::stack +wordChain(std::string &w1, std::string &w2, + const std::unordered_set &dictionary) { + std::unordered_set visited; + std::queue> queue; + { + std::stack first; + first.push(w1); + queue.push(first); + } + visited.insert(w1); + + while (!queue.empty()) { + std::stack 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 nextStack = front; + nextStack.push(nextWord); + queue.push(nextStack); + visited.insert(nextWord); + } + } + } + + return std::stack(); +} + 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 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 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;