Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

a quicker approach to your bit counting routines: (in C because that's what I'm most comfortable with, but it is pretty much a drop-in replacement for your code)

  #include <stdio.h>

  char dist[256];

  hamm_init()

  {
        int i,j,n;

        for (i=0;i<256;i++) {
                j = i;       

                n = 0;
                while (j) {
                        if (j & 1) {
                                n++;
                        }           
                        j >>= 1;    
                }

                dist[i] = n;
        }
  }

  int hamming_distance(char * hash1,char * hash2) {
        //calculate the distance between two hashes

        int d = 0;

        while (*hash1) {
                if (*hash2 == 0) {
                        break;
                }

                d += dist[*hash1++ ^ *hash2++];
        }

        return d;
  }

  main()

  {
        hamm_init();

        printf("0 %d\n",hamming_distance("abcd","abcd"));

        printf("1 %d\n",hamming_distance("accd","abcd"));

  }


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: