/****************************************************************************** * This program compares recursion to iteration in computing palindromes. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include "Utils.hpp" #include #include #include #include #include #include std::locale utf8loc(std::locale(), new std::codecvt_utf8); using namespace Utils; using namespace std; static const vector TEST_CASES = {L"Hannah", L"Able was I ere I saw Elba", L"A man, a plan, a canal – Panama", L"T. Eliot, top bard, notes putrid tang emanating, is sad; I'd assign it a name: gnat dirt upset on drab pot toilet.", L"This is not a palindrome!"}; bool palindrome_recursive0(wstring s) noexcept { int const S_LEN = s.length(); if (S_LEN < 2) { return true; } if ((int)(s[0]) != (int)(s[S_LEN - 1])) { return false; } return palindrome_recursive0(s.substr(1, (S_LEN - 1) - 1)); } bool palindrome_recursive(wstring s) noexcept { wstring s0 = std::regex_replace(s, wregex(L"\\W+"), L""); s0 = Utils::tolower(s0); return palindrome_recursive0(s0); } bool palindrome_iterative(wstring s) noexcept { wstring s0 = std::regex_replace(s, wregex(L"\\W+"), L""); s0 = Utils::tolower(s0); int const S_LEN = s0.length(); for (int x = 0; x <= (S_LEN - 1) / 2; ++x) { if ((int)(s0[x]) != (int)(s0[S_LEN - 1 - x])) { return false; } } return true; } int main(int argc, char **argv) { setlocale(LC_ALL, "en_US.UTF-8"); wcout.imbue(utf8loc); wcin.imbue(utf8loc); for (auto s : TEST_CASES) { wcout << L"Test Case: " << s << endl; bool result = palindrome_recursive(s); wcout << L"palindromeRecursive: " << (result ? L"Yes" : L"No") << endl; result = palindrome_iterative(s); wcout << L"palindromeIterative: " << (result ? L"Yes" : L"No") << endl; } return 0; }