home *** CD-ROM | disk | FTP | other *** search
- #include <iostream.h>
- #include <conio.h>
-
- void ForzaBruta(char *x, int m, char *y, int n) {
- int i, j;
-
- /* Ricerca di forza bruta */
- for (j = 0; j <= n - m; ++j) {
- for (i = 0; i < m && x[i] == y[i + j]; ++i);
- if (i >= m)
- cout<<j<<"\n";
- }
- }
-
- #define EOS '\0'
-
- void ForzaBruta2(char *x, int m, char *y, int n) {
- char *yb;
- /* Ricerca di Forza Bruta migliorato */
- for (yb = y; *y != EOS; ++y)
- if (memcmp(x, y, m) == 0)
- cout<<(y - yb)<<"\n";
- }
-
- #define REHASH(a, b, h) ((((h) - (a)*d) << 1) + (b))
-
- void KarpRabin(char *x, int m, char *y, int n) {
- int d, hx, hy, i, j;
-
- /* Pre-elaborazione */
- /* numero di computazioni d = 2^(m-1)
- con operatore di shift sinistro */
- for (d = i = 1; i < m; ++i)
- d = (d<<1);
-
- for (hy = hx = i = 0; i < m; ++i) {
- hx = ((hx<<1) + x[i]);
- hy = ((hy<<1) + y[i]);
- }
- //cout<<"hx : "<<hx<<"\n\n";
-
- /* Ricerca di Karp Rabin */
- j = 0;
- while (j <= n-m) {
- //cout<<"hy("<<j<<"): "<<hy<<"\n";
- if (hx == hy && memcmp(x, y + j, m) == 0)
- cout<<j<<"\n";
- hy = REHASH(y[j], y[j + m], hy);
-
- ++j;
- }
- }
-
- void preMorrisPratt(char *x, int m, int mpNext[]) {
- int i, j;
-
- i = 0;
- j = mpNext[0] = -1;
- while (i < m) {
- while (j > -1 && x[i] != x[j])
- j = mpNext[j];
- mpNext[++i] = ++j;
- }
- }
-
-
- void MorrisPratt(char *x, int m, char *y, int n) {
- int i, j, mpNext[5];
-
- /* Pre-elaborazione*/
- preMorrisPratt(x, m, mpNext);
-
- /* Ricerca */
- i = j = 0;
- while (j < n) {
- while (i > -1 && x[i] != y[j])
- i = mpNext[i];
- i++;
- j++;
- if (i >= m) {
- cout<<(j - i)<<"\n";
- i = mpNext[i];
- }
- }
- }
-
-
-
-
-
-
-
-
- int main()
- { char wait;
- ForzaBruta("pippo",5,"ho incontrato pippo rossi e pippo bianchi",38);
- ForzaBruta2("pippo",5,"ho incontrato pippo rossi e pippo bianchi",38);
- KarpRabin("pippo",5,"ho incontrato pippo rossi e pippo bianchi",38);
- MorrisPratt("pippo",5,"ho incontrato pippo rossi e pippo bianchi",38);
- cin>>wait;
- }
-