Thread: Hashing In C
View Single Post
Old Feb 21st, 2008, 3:06 AM   #14
Game_Ender
Professional Programmer
 
Game_Ender's Avatar
 
Join Date: May 2006
Location: Maryland, USA
Posts: 306
Rep Power: 3 Game_Ender is on a distinguished road
Re: Hashing In C

This uses the fastest possible associative data structure: an array. That is all you need in this case because you are only dealing with numbers. It could use more memory than the map depending on the ratio of n to the max value of x. It runs in 40% the time of the STL map based version. (Both compiled with -O3)
c Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define MAX_VAL 10000000
  5.  
  6. int main() {
  7. unsigned int n, x, size, mode=0;
  8. unsigned int* counts = calloc(MAX_VAL, sizeof(unsigned int));
  9.  
  10. freopen("mode.in", "rt", stdin);
  11. scanf("%d\n", &n);
  12.  
  13. while (n--) {
  14. scanf("%d\n", &x);
  15. if (( size = ++counts[x]) > mode) mode = size;
  16. }
  17. printf("%d\n", mode);
  18.  
  19. return 0;
  20. }

Just up and learn the STL it will save you a *ton* of time. It will give you tested, debugged, and optimized data structures and algorithms. That is what you want when you are working under pressure. You don't want to lose because you made a stupid error in your linked list or binary tree, you want to be solving the problem. You can find plenty of STL tutorials on google.
__________________
Robotics @ Maryland AUV Team - Software Lead

Last edited by Game_Ender; Feb 21st, 2008 at 3:18 AM.
Game_Ender is offline   Reply With Quote