1
0
LearningCPP/main.cpp

102 lines
3.0 KiB
C++

#include <string>
#include <vector>
#include <thread>
#include <iostream>
#include <atomic>
using atomic_bool = std::atomic_bool;
using thread = std::thread;
using string = std::string;
using svector = std::vector<string>;
using tvector = std::vector<thread>;
void exec_containsSubstring(string&,string&,int,int, atomic_bool&);
bool containsSubstring(string&,string&,int,int);
string prompts(const string&,bool*);
int prompti(const string&,bool*);
int main() {
tvector threads;
svector inputs;
bool s{};
int numt = prompti("Enter the number of threads for searching: ", &s);
if (!s)
return 0;
if (numt < 1) {
std::cout << "Invalid Thread Count!\n";
return 1;
}
string toTest = prompts("Enter the string to search in: ", &s);
if (!s)
return 0;
if (static_cast<int>(toTest.length())/numt == 0) {
std::cout << "Invalid Search String Length!\n";
return 1;
}
string testFor = prompts("Enter the string to search for: ", &s);
if (!s)
return 0;
if (testFor.length() == 0 || testFor.length() > toTest.length()) {
std::cout << "Invalid Searching String Length!\n";
return 1;
}
atomic_bool res{false};
for (int i = 0; i < numt; ++i)
threads.push_back(thread {exec_containsSubstring, std::ref(toTest), std::ref(testFor), i*static_cast<int>(toTest.length())/numt, (i+1)*static_cast<int>(toTest.length())/numt, std::ref(res)});
for (auto &t : threads)
t.join();
std::cout << "String Contained state: " << res.load() << "\n" << std::flush;
return 0;
}
void exec_containsSubstring(string& toTest,string& testFor, int startIndex, int endIndex, atomic_bool& res) {
bool hm {containsSubstring(toTest,testFor, startIndex, endIndex)};
if (hm)
res.store(hm);
}
bool containsSubstring(string& toTest,string& testFor, int startIndex, int endIndex) {
bool matches {true};
while (startIndex < endIndex && startIndex < static_cast<int>(toTest.length())) {
for (int i = 0; i < static_cast<int>(testFor.length()); ++i) {
matches &= toTest[(long long unsigned int)(i+startIndex)] == testFor[(long long unsigned int)i];
if (!matches)
break;
}
if (matches)
return true;
matches = true;
++startIndex;
}
return false;
}
string prompts(const string &message, bool *success) {
string tr{""};
*success = false;
std::cout << message;
if (!(std::getline(std::cin,tr))) {
std::cin.clear();
std::cin.ignore();
return "";
}
*success = true;
return tr;
}
int prompti(const string &message, bool *success) {
int tr{0};
*success = false;
std::cout << message;
if (!(std::cin >> tr)) {
std::cin.clear();
std::cin.ignore();
return 0;
}
*success = true;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return tr;
}