You are on page 1of 2

#include <iostream>

#include <cstring>

using namespace std;

const int prime = 31; // Просте число для хешування


const int INT_MAX = 2147483647; // Максимальне число що зберігається в 32 бітах

int calculateHash(char* str) {


int hashValue = 0;
int len = strlen(str);
for (int i = 0; i < len; ++i) {
hashValue = (hashValue * prime + str[i]) % INT_MAX;
}
return hashValue;
}

void searchPattern(char** text, int* pattern, int n, int m) {

bool found = false;

int patternHash = pattern[0];

// Перевірка кожного рядка в тексті


for (int i = 0; i <= n - m; ++i) { //O((n-m)^2(m-1)m^2) |||

for (int j = 0; j <= n - m; ++j) { //O((n-m)(m-1)m^2)


char* substring = &text[i][j];
int substringHash = calculateHash(substring); //O((m-1)m^2)

if (substringHash == patternHash) {
// Перевірка решти рядків зразка
bool match = true;
for (int k = 1; k < m; ++k) { //O((m-1)m) |||
substring = &text[i + k][j];
substringHash = calculateHash(substring); //O(m) |||

if (substringHash != pattern[k]) {
match = false;
break;
}
}

if (match) {
found = true;
cout << "The pattern was found starting in the row number " << i
+ 1 << ", position in the starting row is " << j + 1 << endl;
}
}
}
}
if(!found){
cout << "The pattern was not found in the array" << endl;
}
}

int main() {

int n, m;
cout << "Enter the size of array n - ";
cin >> n;

char** text = new char*[n];

cout << "Enter the array nxn:" << endl;


for(int i=0; i<n; i++){
text[i] = new char[n];
cin >> text[i];
}

cout << "Enter the size of pattern m - ";


cin >> m;

char** pattern_str = new char*[m];


int* pattern = new int[m];

cout << "Enter the pattern mxm:" << endl;


for(int i=0; i<m; i++){
pattern_str[i] = new char[m];
cin >> pattern_str[i];
}

//Хеш-значення для рядків паттерна, складність O(m^m)


for(int i=0; i<m; i++){
pattern[i] = calculateHash(pattern_str[i]);
}

searchPattern(text, pattern, n, m);

return 0;
}

You might also like