Advertisement
Guest User

hash

a guest
Oct 27th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct zaznam {
  6.   char ID[9];
  7.   struct zaznam *dalsi;
  8. } ZAZNAM;
  9.  
  10. int hash(char *string)
  11. {
  12.   int i, len, result=1;
  13.   len = strlen(string);
  14.   for (i=0; i<len; i++)
  15.   {
  16.     if (i != 0)
  17.     {
  18.       result = result*2 + string[i];
  19.     }
  20.     else
  21.     {
  22.       result = string[i];
  23.     }
  24.   }
  25.   return result;
  26. }
  27.  
  28. // spracuje cisla OP: vrati pocet najdenych duplikatov.
  29. int vyhadzovac(char *a[], int n)
  30. {
  31.   ZAZNAM **pole = (ZAZNAM**)malloc(5*n*sizeof(ZAZNAM*));
  32.   int pocet=0, i, hashCode;
  33.   ZAZNAM *pom;
  34.   for (i=0; i<5*n; i++)
  35.   {
  36.     pole[i] = NULL;
  37.   }
  38.   for (i=0; i<n; i++)
  39.   {
  40.     hashCode = hash(a[i]);
  41.     if (pole[hashCode % (5*n)] == NULL)
  42.     {
  43.       pole[hashCode % (5*n)] = malloc(sizeof(ZAZNAM));
  44.       strcpy(pole[hashCode % (5*n)] -> ID, a[i]);
  45.       pole[hashCode % (5*n)] -> dalsi = NULL;
  46.     }
  47.     else
  48.     {
  49.       pom = pole[hashCode % (5*n)];
  50.       while (pom-> dalsi != NULL)
  51.       {
  52.         if (strcmp(pom -> ID, a[i]) == 0)
  53.         {
  54.           pocet+=1;
  55.           break;
  56.         }
  57.         else
  58.         {
  59.           pom = pom -> dalsi;
  60.         }
  61.       }
  62.       if (pom -> dalsi == NULL)
  63.       {
  64.         if (strcmp(pom -> ID, a[i]) == 0)
  65.         {
  66.           pocet+=1;
  67.         }
  68.         else
  69.         {
  70.           pom -> dalsi = malloc(sizeof(ZAZNAM));
  71.           strcpy(pom -> dalsi -> ID, a[i]);
  72.           pom -> dalsi -> dalsi = NULL;
  73.         }
  74.       }
  75.     }
  76.   }
  77.   return pocet;
  78. }
  79.  
  80. // ukazkovy test
  81. int main(void)
  82. {
  83.   char **a = NULL, buf[100];
  84.   int n = 0, len = 0;
  85.  
  86.   // nacitanie retazcov
  87.   while(scanf("%s", buf) > 0)
  88.   {
  89.     if (n == len)
  90.     {
  91.       len = len + len + (len==0);
  92.       a = (char**)realloc(a, len*sizeof(char*));
  93.     }
  94.     a[n++] = strdup(buf);
  95.   }
  96.   printf("Pocet duplikatov: %d\n", vyhadzovac(a, n));
  97.   return 0;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement