Guest User

Untitled

a guest
Jul 20th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.79 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <stdlib.h>
  3. #include <iostream>
  4. #include <conio.h>
  5. #include <string>
  6. #include <windows.h>
  7. #include <stdio.h>
  8.  
  9. #define HASH_MULTIPL 128 //Кратность хэша
  10.  
  11. struct stWord
  12. {
  13.     int n_start;        //Номер первой буквы слова в тексте
  14.     int n_end;          //Номер последнией буквы
  15.     std::string word_s; //Само слово
  16.     stWord* next;
  17. };
  18.  
  19. void Read_file(FILE*);
  20. int Symbol_number(FILE*);
  21. int Calc_hash(char* );
  22. stWord* Add_word(int );
  23. void Fill_hash(char* );
  24. void View_hash(void);
  25. void Search(std::string );
  26.  
  27. int val_sym,val_word;
  28. char* cText;
  29. stWord *Hash[HASH_MULTIPL];
  30.  
  31. using namespace std;
  32.  
  33. HANDLE  hStdout = GetStdHandle (STD_OUTPUT_HANDLE);
  34.  
  35. int _tmain(int argc, _TCHAR* argv[])
  36. {
  37.     setlocale (LC_CTYPE, "Russian");
  38.     //Открываем файл и записываем его содержимое в массив
  39.     FILE* fText;
  40.     fText=fopen("text.txt","r");
  41.     if (!fText)
  42.     {
  43.         SetConsoleTextAttribute (hStdout, 12);
  44.         cout<<"Файл не найден\n";
  45.         SetConsoleTextAttribute (hStdout, 7);
  46.         return 0;
  47.     }
  48.     val_sym=Symbol_number(fText);
  49.     cText=(char*)malloc(val_sym+2);
  50.     fText=fopen("text.txt","r");
  51.     Read_file(fText);
  52.     fclose(fText);
  53.  
  54.     Fill_hash(cText);
  55.  
  56.     cout<<cText<<endl<<endl;
  57.     SetConsoleTextAttribute (hStdout, 15);
  58.     cout<<"Поиск: ";
  59.     string key;
  60.     cin>>key;
  61.     SetConsoleTextAttribute (hStdout, 7);
  62.     cout<<endl;
  63.     SetConsoleTextAttribute (hStdout, 15);
  64.     cout<<"--------------------------------------------------------------------------------";
  65.     SetConsoleTextAttribute (hStdout, 7);
  66.     Search(key);
  67. }
  68.  
  69. void Read_file(FILE*text)
  70. {
  71.     int i;
  72.     cText[0]=' ';
  73.     for (i=1; i<=val_sym;i++)
  74.         cText[i]=fgetc(text);
  75.     cText[i]='\0';
  76. }
  77.  
  78. int Symbol_number(FILE*text)
  79. {
  80.     text=fopen("text.txt","r");
  81.     int n=0;
  82.     char ch;
  83.     while((ch=fgetc(text))!=EOF)
  84.         n++;
  85.     fclose(text);
  86.     if (n==0)
  87.     {
  88.         SetConsoleTextAttribute (hStdout, 12);
  89.         cout<<"Файл пуст\n";
  90.         SetConsoleTextAttribute (hStdout, 7);
  91.         exit(1);
  92.     }
  93.     return n;
  94. }
  95.  
  96. int Calc_hash(char* tmp)
  97. {
  98.     int sum=0;
  99.     while ((*tmp>='A')&&(*tmp<='z'))
  100.     {
  101.         sum+=(*tmp);
  102.         tmp++;
  103.     }
  104.     return sum%HASH_MULTIPL;
  105. }
  106.  
  107. void Fill_hash(char* text)
  108. {
  109.     int i;
  110.     int nStart=0,nEnd=0,hash=0; //Номер буквы начала и конца слова, хэш-сумма слова
  111.     stWord* tmpWord=0;          //Указатель для создания нового элемента списка
  112.  
  113.     for(i=1;i<=val_sym;i++)//Идём по всему тексту по буквам
  114.     {
  115.         if ((cText[i]>='A')&&(cText[i]<='z')&&((cText[i-1]<'A')||(cText[i-1]>'z')))//Встретили начало слова
  116.         {
  117.             nStart=i;
  118.             hash=Calc_hash(cText+nStart);
  119.         }
  120.         if (((cText[i+1]<'A')||(cText[i+1]>'z'))&&(nStart!=0))  //Встретили конец слова
  121.         {
  122.             nEnd=i;
  123.             tmpWord=Add_word(hash); //Добавили новый элемент в списко с номером hash
  124.  
  125.             //И заполнили:
  126.             tmpWord->n_end=nEnd;
  127.             tmpWord->n_start=nStart;
  128.             (tmpWord->word_s).insert(0,cText,nStart,(nEnd-nStart+1));
  129.  
  130.             nStart=0;
  131.         }
  132.     }
  133. }
  134.  
  135. stWord* Add_word(int hash)
  136. {
  137.     stWord* newWord=new stWord; //Выделяется память под слово
  138.     newWord->next=0;            //Новый элемент - хвост списка
  139.     if(Hash[hash]==0)//Если списко был пуст, то новый элемент - начало списка
  140.     {
  141.         Hash[hash]=newWord;
  142.     }
  143.     else
  144.     {
  145.         stWord* tmp;
  146.         tmp=Hash[hash];
  147.         while(tmp->next!=0) tmp=tmp->next;//Иначе ищем конец списка
  148.         tmp->next=newWord;//И присоединяем новый элемент в конец списка
  149.     }
  150.     return newWord;
  151. }
  152.  
  153. void View_hash(void) //Вспомогательная функция, выводит на экран содержимое хэша
  154. {
  155.     int i;
  156.     stWord* ptr;
  157.     for (i=0;i<HASH_MULTIPL;i++)
  158.     {
  159.         if(Hash[i]!=0)
  160.         {
  161.             ptr=Hash[i];
  162.             printf("hash %i -",i);
  163.             do
  164.             {
  165.                 printf(" %i %i  ",  ptr->n_start, ptr->n_end);
  166.                 cout<<ptr->word_s<<"   |   ";
  167.                 ptr=ptr->next;
  168.             }while(ptr!=0);
  169.         }
  170.         else printf("hash %i - empty", i);
  171.         printf("\n");
  172.     }
  173. }
  174.  
  175. void Search(string sWord)
  176. {
  177.     int i,match=0;
  178.     stWord* hashedWords;    //Указатель для перемещения по нужному списку
  179.     int wHash;              //Хэш sWord
  180.     int len=sWord.length();
  181.     char* cWord=(char*)malloc(len); //sWord будет в форме строки-массива
  182.     sWord.copy(cWord,len,0);        //Копируем
  183.     wHash=Calc_hash(cWord);         //Чтобы посчитать хэш
  184.     hashedWords=Hash[wHash];        //И переходим к нужному списку
  185.  
  186.     if(!Hash[wHash])//Указатель на голову списка нулевой - результатов заведомо нет
  187.     {
  188.         cout<<cText<<endl;
  189.         SetConsoleTextAttribute (hStdout, 15);
  190.         cout<<"Совпадений не найдено"<<endl;
  191.         SetConsoleTextAttribute (hStdout, 7);
  192.         return;
  193.     }
  194.  
  195.     for(i=1;i<=val_sym;i++)//Выводим текст посимвольно
  196.     {
  197.         if((i==(hashedWords->n_start))&&(!(hashedWords->word_s.compare(sWord))))
  198.         {
  199.             SetConsoleTextAttribute (hStdout, 224); //Включая подсветку в начале каждого совпадения
  200.             match++;
  201.         }
  202.         if(i==hashedWords->n_end+1)
  203.         {
  204.             SetConsoleTextAttribute (hStdout, 7);   //И выключая в конце
  205.             if(hashedWords->next)
  206.             hashedWords=hashedWords->next;          //Не забываем бежать по списку
  207.         }
  208.     putch(cText[i]);
  209.     }
  210.  
  211.     //Выводим количество совпадений
  212.     SetConsoleTextAttribute (hStdout, 15);
  213.     if(!match)
  214.         cout<<endl<<"Совпадений не найдено"<<endl;
  215.     else
  216.         cout<<endl<<"Совпадения: "<<match<<endl;
  217.     SetConsoleTextAttribute (hStdout, 7);
  218. }
Add Comment
Please, Sign In to add comment