Tuesday 28 June 2011

::::|| VU ||:::: CS301_Assign_04_2_Idea_Solutions

//In order to work file , you need to create a file named"input.dat" through notepad, and //place in the folder where this huffman_encoding.exe is placed.

//this is working file.it image is attachecd in the solution file.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>
#include <conio.h>

using namespace std;

struct node {
int weight;
unsigned char value;
const node *child0;
const node *child1;

node( unsigned char c = 0, int i = -1 ) {
value = c;
weight = i;
child0 = 0;
child1 = 0;
}

node( const node* c0, const node *c1 ) {
value = 0;
weight = c0->weight + c1->weight;
child0 = c0;
child1 = c1;
}

bool operator<( const node &a ) const {
return weight >a.weight;
}

void traverse(string code="") const {

if ( child0 ) {
child0->traverse( code + '0' );
child1->traverse( code + '1' );
} else {
cout <<" " <<value <<" ";
cout <<weight;
cout <<" " <<code <<endl;
}
}

};



void count_chars( int *counts )
{
for ( int i = 0 ; i <256 ; i++ )
counts[ i ] = 0;
ifstream file( "input.dat" );
if ( !file ) {
cout <<"Couldn't open the input file!\n";
throw "abort";
}
file.setf( ios::skipws );
for ( ; ; ) {
unsigned char c;
file>> c;
if ( file )
counts[ c ]++;
else
break;
}
}

int main()
{
cout<<"Huffman Encoding Algorithm"<<endl;
cout<<"Welcome to Virtual University"<<endl;
cout<<"==================================="<<endl;
int counts[ 256 ];
count_chars( counts );
priority_queue < node > q;

for ( int i = 0 ; i <256 ; i++ )
if ( counts[ i ] )
q.push( node( i, counts[ i ] ) );

while ( q.size() >1 ) {
node *child0 = new node( q.top() );
q.pop();
node *child1 = new node( q.top() );
q.pop();
q.push( node( child0, child1 ) );
}

cout <<"CHAR FREQUENCY HOFFMAN-CODE" <<endl;
q.top().traverse();
getche();
return 0;

}


اسلام علیکم ورحمتہ اللہ و برکاتہ

Plz find attachment.
Two solution are attached.
Huffman encoding program is also attached which is working.tested by me......


Best Wishes,
"...SUBHANALLAHI WABI HAMDIHI...SUBHANALLAH IL AZEEM..."
Muhammd Ishfaq
MCS 2nd Semester (PakPattan)



--
For study materials, past papers and assignments,
Join VU School at www.VusCool.com
and www.VUGuys.com
CoooL Virtual University Students Google Group.
To post to this group, send email to coool_vu_students@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/coool_vu_students?hl=en

No comments:

Post a Comment