Advertisement
nbaztec

Untitled

Aug 19th, 2012
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <string.h>
  4.  
  5. #define MAX_WORDS 50
  6. #define MAX_WORD_LEN 25
  7.  
  8. using namespace std;
  9.  
  10. struct HashItem
  11. {
  12.     char *str;
  13.     int count;
  14. };
  15.  
  16. int add_word(char *w, HashItem *list, int sz)
  17. {
  18.     for(int i=0; i<sz; i++)
  19.         if(strcmpi(w, list[i].str) == 0)
  20.         {
  21.             list[i].count += 1;
  22.             return 0;
  23.         }
  24.     list[sz].str = w;
  25.     list[sz].count = 1;
  26.     return 1;
  27. }
  28.  
  29. HashItem get_max(HashItem *list, int sz)
  30. {
  31.     HashItem item;
  32.     int max = -1;
  33.     for(int i=0; i<sz; i++)
  34.             if(list[i].count > max)
  35.             {
  36.                 item = list[i];
  37.                 max = item.count;
  38.             }
  39.     return item;
  40. }
  41.  
  42. int main(int argv, char **argc)
  43. {
  44.     HashItem *list = new HashItem[MAX_WORDS];
  45.     int sz = 0;
  46.  
  47.     // Sample Input
  48.     char in_str[] =
  49.                     "foo bar baz "
  50.                     "int foo bar foo";
  51.     char *str = in_str;
  52.     char *token = NULL;
  53.     while(token = strtok(str, " "))
  54.     {
  55.         str = NULL;
  56.         sz += add_word(token, list, sz);
  57.  
  58.     }
  59.  
  60.     // See the list
  61.     for(int i=0; i<sz; i++)
  62.         cout<<list[i].str<< ", " <<list[i].count<<endl;
  63.  
  64.     // Obtain Max
  65.     HashItem item = get_max(list, sz);
  66.     cout<<"Max occurrence: "<< item.str << " ("<<item.count<<")";
  67.     delete list;
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement