#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ABC_LEN 26
typedef int FrequencyTable[ABC_LEN + 1];
void initFrequencyTable( FrequencyTable tbl )
{
int i;
for( i=0; i<ABC_LEN; i++ )
tbl[i] = 0;
}
void createFrequencyTable( FrequencyTable tbl, const char *s1 )
{
const char *p = s1;
while( *p != '\0' )
{
tbl[(*p - 'a')]++;
p++;
}
tbl[ABC_LEN] = strlen( s1 );
}
float matchFrequency( FrequencyTable f1, FrequencyTable f2 )
{
int difference = 0;
int i, n1, n2;
int biggest = 0;
int len1, len2;
len1 = f1[26]; len2 = f2[26];
if( len1 ^ len2 ) //one of them are zero
return 0;
else if( !len1 && !len2 )
return 1;
for( i=0; i<ABC_LEN; i++ )
{
n1 = f1[i]; n2 = f2[i];
if( n1 && n2 )
{
if( n1 == n2 )
difference += n1;
else if( n1 > n2 )
difference += n2;
else
difference += n1;
}
}
if( len1 > len2 ) {
biggest = len1;
}
else if( len1 < len2 ) {
biggest = len2;
}
else {
biggest = len2;
}
return (float)((float)difference / (float)biggest);
}
void chomp( char *s )
{
char *p;
p = strrchr( s, '\n' );
if( p ) *p = '\0';
}
int main( void )
{
FrequencyTable f1, f2;
char strOne[1024], strTwo[1024];
int biggest = 0;
printf( "insert string one:\n#>" );
fgets( strOne, sizeof( strOne ), stdin ); chomp( strOne );
printf( "insert string two:\n#>" );
fgets( strTwo, sizeof( strTwo ), stdin ); chomp( strTwo );
printf( "comparing <%s> with <%s>\n", strOne, strTwo );
initFrequencyTable( f1 );
initFrequencyTable( f2 );
createFrequencyTable( f1, strOne );
createFrequencyTable( f2, strTwo );
printf( "They match %.2f%%!\n", matchFrequency( f1, f2 ) * 100.0 );
return 0;
}