#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAX 127
#define SIZE 100
struct element
{
char c;
float pr;
float rng;
float UL;
float LL;
}el[MAX];
int size;
char msg[SIZE];
float range = 1.00;
float UP;
float DOWN;
float enc;
int str_len;
void make_table()
{
int i;
printf(" Enter the size of elements : ");
scanf("%d",&size);
fflush(stdin);
for(i=0;i<size;i++)
{
printf("\n #%d Enter character and its probablity (decreasing order) : ",i+1);
scanf("%c %f",&el[i].c,&el[i].pr);
fflush(stdin);
el[i].LL = ((i==0) ? 0.0 :el[i-1].UL);
el[i].UL = ((i==size-1) ? 1.0 : (el[i].LL + el[i].pr));
}
getch();
}
void show_table(int num)
{
printf("\t\tENCODER TABLE\n\tFrequency\tRange\n");
for(int i=0;i<size;i++)
{
printf("\n");
if(i==num)
{ printf("*"); }
printf("%c\t%f\t%f-%f",el[i].c,el[i].pr,el[i].LL,el[i].UL);
}
}
int find_char(int num)
{
int i=0;
if(num != -1)
{
while(el[i].c != msg[num])
{ i++; }
}
else
{
while(!(enc <= el[i].UL && enc >= el[i].LL))
{ i++; }
}
return i;
}
void modify_table(int num)
{
range = el[num].UL - el[num].LL;
for(int i=0;i<size;i++)
{
el[i].LL = ((i==0) ? el[num].LL : el[i-1].UL) ;
el[i].UL = ((i==size-1) ? (el[0].LL+range) : (el[i].LL + (el[i].pr*range)));
}
}
void refresh_table()
{
for(int i=0;i<size;i++)
{
el[i].LL = ((i==0) ? 0.0 :el[i-1].UL);
el[i].UL = ((i==size-1) ? 1.0 : (el[i].LL + el[i].pr));
}
}
void encode_text()
{
fflush(stdin);
printf("\n Enter the string to be encoded : ");
gets(msg);
fflush(stdin);
int i=0;
int j;
while(msg[i] != '\0')
{
printf("\n\n\n Word Checked : %c \n",msg[i]);
j = find_char(i);
show_table(j);
modify_table(j);
getch();
i++;
}
DOWN = el[j].LL;
UP = el[j].UL;
str_len = i;
printf("\n\n The encoded range : %f-%f for a string of %d characters",DOWN,UP,str_len);
refresh_table();
}
void decode_text()
{
int j;
printf("\n Enter the encoded value : ");
scanf("%f",&enc);
fflush(stdin);
printf("\n\n ... Decoding Text ... \n\n");
while(str_len)
{
j = find_char(-1);
printf("\n\n Word decoded : %c",el[j].c);
enc = (enc - el[j].LL)/(el[j].UL - el[j].LL);
printf("\n New encoded value : %f",enc);
str_len--;
}
}
int main()
{
int cho;
do
{
printf("\n\n\n\t MENU \t\n");
printf("\n1. Create Table ");
printf("\n2. Encode Text ");
printf("\n3. Decode Text ");
printf("\n\n Choose the option : ");
scanf("%d",&cho);
switch(cho)
{
case 1 : make_table(); break;
case 2 : encode_text(); break;
case 3 : decode_text(); break;
default : break;
}
}while(cho>=1 && cho<=3);
printf("\n\n\t Thanks for using the Program !! \t\n\n");
return 0;
}
No comments:
Post a Comment