Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- int moduloPower(int first, int second, int modulus) {
- int result = 1;
- long tmp = first%modulus;
- for (int i = 1; i <= second; i <<= 1) {
- tmp %= modulus;
- if ((second&i) != 0) {
- result *= tmp;
- result %= modulus;
- }
- tmp *= tmp;
- }
- return result%modulus;
- }
- int main() {
- int totalNumberOfCharacters = 256;
- int primeNumber = 101;
- int numberOfFiles;
- int patternLenght, textLenght, hash1, hash2, rm, i, j;
- std::string downloadedString;
- std::string tmpPattern;
- std::string tmpFileName;
- std::string tmpText;
- std::vector<std::string> vectorFiles;
- std::vector<std::string> vectorPatterns;
- std::ifstream file;
- std::cin >> downloadedString;
- try {
- numberOfFiles = stoi(downloadedString);
- }
- catch (...) {
- std::cout << "fail to convert value (numberOfFiles)" << std::endl;
- return EXIT_FAILURE;
- }
- for (int i = 0; i < numberOfFiles; i++) {
- std::cin >> downloadedString;
- vectorFiles.push_back(downloadedString);
- std::cin >> downloadedString;
- vectorPatterns.push_back(downloadedString);
- }
- for (int counter = 0; counter < numberOfFiles; counter++) {
- tmpPattern = vectorPatterns[counter];
- std::cout << tmpPattern << std::endl;
- tmpFileName = vectorFiles[counter];
- std::cout << tmpFileName << std::endl;
- file.open(tmpFileName, std::ios::in);
- if (file.good() == true)
- {
- tmpText.assign((std::istreambuf_iterator<char>(file)),
- (std::istreambuf_iterator<char>()));
- file.seekg(0, std::ios_base::beg);
- file.close();
- }
- else std::cout << "Cannot open file: " << tmpFileName << std::endl;
- textLenght = tmpText.length();
- patternLenght = tmpPattern.length();
- hash2 = 0;
- hash1 = 0;
- for (i = 0; i<patternLenght; i++)
- {
- hash2 = ((hash2*totalNumberOfCharacters) + tmpText[i]);
- hash2 %= primeNumber;
- }
- for (i = 0; i<patternLenght; i++)
- {
- hash1 = ((hash1*totalNumberOfCharacters) + tmpText[i]);
- hash1 %= primeNumber;
- }
- rm = moduloPower(totalNumberOfCharacters, patternLenght - 1, primeNumber);
- i = 0;
- while (i < textLenght - patternLenght)
- {
- j = 0;
- if (hash1 == hash2) while ((j<patternLenght) && (tmpPattern[j] == tmpText[i + j])) j++;
- if (j == patternLenght) {
- std::cout << i << " ";
- }
- hash2 = ((hash2 - tmpText[i] * rm)*totalNumberOfCharacters + tmpText[i + patternLenght]);
- hash2 %= primeNumber;
- if (hash2 < 0) {
- hash2 += primeNumber;
- }
- i++;
- }
- j = 0;
- if (hash1 == hash2) {
- while ((j < patternLenght) && (tmpPattern[j] == tmpText[i + j])) j++;
- }
- if (j == patternLenght) {
- std::cout << i << " ";
- }
- std::cout << std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement