[ create a new paste ] login | about

Link: http://codepad.org/ratzGr6P    [ raw code | output | fork | 1 comment ]

joshua_cheek - C, pasted on Oct 23:
//returns the number of matches, where a match is some character in both strings
int find_match( char m[] , char s[] )
{
  //using 384 because it guarantees that no matter how the compiler interprets a char
  //it will have enough room. The union of possible domains should be -128 through 255
  int matches[384] , i;
  for( i=0 ; i<384 ; ++i )  matches[i] = 0;            //initial sum is zero matches for any char
  
  //offset by 128 in case compiler made it negative
  //we are just creating a sum for every character in m
  //then we cycle through the array, and for every character we find,
  //we increment it's sum                                                
  for( i=0 ; m[i] ; ++i ) ++matches[m[i]+128];         
  
  //now that we have the sums of every character in m, we need to find the ones we care about
  //so for every char in s, we look in matches to see how many times it occurred in m
  //then we add that to our total sum of all matches.
  //note: if some character is in s more than one time, then it will match against m that many times
  //so if m="abcabc" and s="aa" then there will be four matches, because each of the two a's in s
  //match against each of the two a's in m
  int sum = 0;
  for( i=0 ; s[i] ; ++i ) sum += matches[s[i]+128];
  return sum;
}

int main (int argc, char const *argv[])
{
  char m[]="abcdefg" , s[] = "adf";
  printf( "m = \"%s\"\ns = \"%s\"\n" , m , s );
  printf( "There are %d matches\n" , find_match(m,s) );
  return 0;
}


Output:
1
2
3
m = "abcdefg"
s = "adf"
There are 3 matches


Create a new paste based on this one


Comments:
posted by joshua_cheek on Nov 15
Counts number of characters shared by two strings.
reply