1

I have a list of (alphabetical) strings, and I want to compare a string against a list of other strings, and find which string has the lowest Hamming distance compared to that string. Also, the list of strings used for comparison is known at compile time.
I thought of something like this:

char* compare[10][10]; // Assume this array is filled with random strings, every string of length n is in row n - 1. 
int hamming_distance(char* x, char* y, int len); // I don't know of any fast ways to compute the Hamming distance between two alphabetical strings
int hamming_distance(char* x, char* y, int len) {
    int hamming_distance = 0;
    for(i = 0; i <= len; i++) {
        if(x[i] != y[i]) {
            hamming_distance++;
        }
    }
    return hamming_distance;
}
char* lowest_hamming_distance(char* x);
char* lowest_hamming_distance(char* x) {
    int minhammingdistance = INT_MAX;
    int currenthammingdistance;
    int len = strlen(x) - 1;
    for( i = 0; i < 10; i++) {
        currenthammingdistance = hamming_distance(compare[len][i], x, len);
        if(minhammingdistance > currenthammingdistance) {
            minhammingdistance = currenthammingdistance;
            int min_hamming_distance_string = i;
        }
    }
    return compare[len][min_hanmming_distance_string];
}
Mitsos101
  • 551
  • 3
  • 15
  • 3
    You blacked-out there? – trincot May 01 '16 at 11:15
  • Add the [tag:algorithm] tag if you want a concept. What is wrong with your current algorithm? (If so.) – Jongware May 01 '16 at 11:22
  • @trincot Oops, I clicked on Submit accidentally – Mitsos101 May 01 '16 at 11:25
  • @RadLexus I'm asking whether there's a fast way to find the Hamming distance between two strings, and if there's a faster way to do the comparison, other than my current algorithm. – Mitsos101 May 01 '16 at 11:29
  • Compare string lengths, if different return `-1`. Let `total = 0` Iterate over each `char` in both _Strings_ (at the same time), if left char does not equal right char, `total += 1`. Return `total` – Paul S. May 01 '16 at 11:32
  • 1
    @Mitsos101, please put the question you gave in comments, in your ... question. Because there you are not asking anything. NB: The algorithm you have for `hamming_distance` after your latest edit, is *O(n)*, which cannot be improved (as you need to verify each character anyway). – trincot May 01 '16 at 11:38
  • `for(i = 0; i <= len; i++) {` this accesses the string beyond its size. – wildplasser May 01 '16 at 11:40
  • @wildplasser How so? The len parameter passed to the function is equal to the length - 1. – Mitsos101 May 01 '16 at 12:27
  • This `compare[len][i]` should probably be just `compare[i]` – Ray May 01 '16 at 14:58
  • @Ray I don't think so, it's an array of string literals. – Mitsos101 May 01 '16 at 17:20

0 Answers0