Vous êtes sur la page 1sur 3

#include<stdio.

h>
#include<math.h>
#include<string.h>

void sort(int);
void divide(int,int);
void eff(int);
int check_duplicate(int j, int i);

struct shanfan
{
char symbol[10];
float prob;
char code[10];
int count;
int length;
}a[25];

char input[15];

int main()
{
int i,j,ctr,si,l,c,k=0,cnt=0,n=0;
char temp1[]={' ','\0'};
float p;

printf("\n\t\t*******SHANON FANO's Source Coding Algorithm*******");


printf("\n\tEnter the string: \t");
gets(input);
l=strlen(input);
printf("The stringlength is %d",l);

for(i=0;i<l;i++) {
ctr=0;
c=check_duplicate(i,l);
if(c==0)
cnt++;
for(j=0;j<l;j++)
{
if(c==0)
{
if(input[i]==input[j])
ctr++;
}
else if(c==1)
break;
}
if(c==0)
{
p=ctr/(float)l;
a[n].prob=p;
a[n].symbol[k]=input[i];
n++;
}
}
sort(cnt);
for(i=0;i<cnt;i++) {
a[i].count=0;
a[i].length = 0;
}

i=0;

divide(i,cnt);
printf("\n The required code using shanon fano's algorithm is");
printf("\nsyambol \t prbability \t code \t length");

for(i=0;i<cnt;i++) {
printf("\n %s \t %f \t%s \t
%d",a[i].symbol,a[i].prob,a[i].code,a[i].length);
}
eff(cnt);
return 0;
}

void sort(int n)
{ int i,j;
struct shanfan temp;
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j].prob<a[j+1].prob)
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}

void divide(int i,int n)


{
char temp1[]={'0','\0'};
char temp2[]={'1','\0'};
float p=0,pl;
int j,k,l;

if((n-i)>=2)
{
for(j=i;j<n;j++)
{
p=p+a[j].prob;
}
pl=p/2-p/10;
p=0;
for(j=i;j<n;j++)
{
p=p+a[j].prob;
if(p>=pl)
break;
}
for(k=i;k<=j;k++)
{
strcat(a[k].code,temp1);
a[k].length++;
a[k].count++;
}
for(k=j+1;k<n;k++)
{
strcat(a[k].code,temp2);
a[k].count++;
a[k].length++;
}
l=i;
divide(l,j+1);
divide(j+1,n);
}
}

void eff(int n)
{
int p,q,b[10];
float r=0.00,ef,ef1,hx=0.00;

for(p=0;p<n;p++) {
hx=hx-1*a[p].prob*(log10(a[p].prob)/log10(2));
}
for (p=0;p<n;p++)
{
r=r+a[p].count*a[p].prob;
}
printf("\n\n H(x)=%fbits/symbol\n\n
rbar=%fbits/symbol\n",hx,r);
ef=hx/r;
printf("\n The efficiency for above code is %f\n",ef);
ef1=ef*100;
printf("\n Hence Percent efficiency is %f%\n",ef1); }

int check_duplicate(int j, int i)


{
int k;
for(k=j+1;k<i;k++)
{
if(input[j]==input[k])
return 1;
}
return 0;
}

Vous aimerez peut-être aussi