Advertisement
BanyRule

Untitled

Sep 21st, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <math.h>
  5. #define tonum(c) (c >= 'A' && c <= 'Z' ? c - 'A' : c - 'a' + 26)
  6.  
  7. int rabin_kapr_matcer(char *Text, char *Pattern, int d, int q) {
  8.     int n = strlen(Text);
  9.     int m = strlen(Pattern);
  10.     int h = (int) pow(d, m - 1) % q;
  11.     int p = 0;
  12.     int t = 0;
  13.     int found = 0;
  14.    
  15.  
  16.     int i = 0;
  17.     int j = 0;
  18.     int s = 0;
  19.  
  20.     //предварительная обработка
  21.     for (int i = 1; i < m; i++){
  22.         p = (d * p + tonum(Pattern[i])) % q;
  23.         t = (d * t + tonum(Text[i])) % q;
  24.     }
  25.    
  26.     //Проверка
  27.     for (int i = 0; i <= n; i++) {
  28.         if (p == t) {
  29.             found = 1;
  30.             for (j = 0; j < m; j++) {
  31.                 if (Pattern[j] != Text[i + j]) {
  32.                     found = 0;
  33.                     break;
  34.                 }
  35.             }
  36.             if (found)
  37.                 return i + 1;
  38.         }
  39.         else {
  40.             t = (d*(t - ((tonum(Text[i])*h) % q)) + tonum(Text[i + m])) % q;
  41.         }
  42.    
  43.     }
  44.  
  45.     return -1;
  46. }
  47.  
  48.  
  49. int main() {
  50.  
  51.     int find;
  52.     int d = 1, q = 1;
  53.     char *T = "Одно из простейших практических применений алгоритма Рабина — Карпа состоит в определении плагиата. Скажем, например, что студент пишет работу по Моби Дику. Коварный профессор находит различные исходные материалы по Моби Дику и автоматически извлекает список предложений в этих материалах.";
  54.     char *P = "Моби";
  55.  
  56.     find = rabin_kapr_matcer(T, P, d, q);
  57.     if (find)
  58.         printf("%d\n", find);
  59.     else
  60.         printf("=(((");
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement