Advertisement
B1KMusic

Hashing Algorithm Experiement (Source Code)

Mar 11th, 2016
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. /*
  2.  * Author:         Braden Best (2016)
  3.  *
  4.  * License:        Do whatever you want unless it's illegal. Please don't use my source code to harvest livers or build a death ray.
  5.  *
  6.  * Description:    This is an experiment to test a hypothesis about collisions in Java's hashCode() function.
  7.  *
  8.  * The experiment: Given the same algorithm, will the inputs "DB" and "Ca" generate the same output?
  9.  *
  10.  * Result:         Success
  11.  */
  12.  
  13. #include <stdio.h>
  14. #include <string.h>
  15.  
  16. int
  17. power(int a, int b){
  18.     int total = a,
  19.         base = b - 1;
  20.  
  21.     if(b == 0)
  22.         return 1;
  23.  
  24.     if(b == 1)
  25.         return a;
  26.  
  27.     while(base){
  28.         total *= a;
  29.         base--;
  30.     }
  31.  
  32.     return total;
  33. }
  34.  
  35. int
  36. hashCode(char *str)
  37. {
  38.     char *p = str;
  39.     int total = 0;
  40.  
  41.     while(*p){
  42.         total += (*p) * power(31, strlen(str) - (1 + (p-str)));
  43.         p++;
  44.     }
  45.  
  46.     return total;
  47. }
  48.  
  49. int
  50. main()
  51. {
  52.     printf("DB: %u\n", hashCode("DB"));
  53.     printf("Ca: %u\n", hashCode("Ca"));
  54.     printf("tt: %u\n", hashCode("tt"));
  55.     printf("Russian Dancing Men: %u\n", hashCode("Russian Dancing Men"));
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement