All pastes #707499 Raw Edit

Unnamed

public text v1 · immutable
#707499 ·published 2007-09-22 23:49 UTC
rendered paste body
// Calculates Entropy for a given file of characters.

import java.lang.Exception;
import java.io.IOException;
import java.io.PrintStream;

class Entropy{

public static void main (String args[])  throws java.lang.Exception  
{	String infile;
	IO.Compressor io ; 
	int i;
	char[] temparray;
	//char[] carray;
	int carrayLength, temparrayLength;
	int [] occurrences = new int[128];
	float entropy = 0;
	try
	{	infile = args[0];	/*infile is the name of the file to be compressed*/ 

		/* Initialize a IO.Compressor object so that it is ready to 
		* read the input file, and to write the output file to the disk */ 
		io = new IO.Compressor(infile); 
		/* Read all characters from the input file to a character array */ 
		temparray = io.giveArray(); 
		
		temparrayLength = temparray.length;
		// Strip 0(NULL) and 10(LF) from end of array
		while( (temparray[temparrayLength-1] == 0) || (temparray[temparrayLength-1] == 10) )
		{	temparrayLength--;
		}
		
		char [] carray = new char[temparrayLength];
		
		for( i = 0; i < temparrayLength; i++)
		{	carray[i] = temparray[i];
		}
		
		carrayLength = carray.length;
		//System.out.println ("Length of String = " + carrayLength);
		for(i = 0; i< carrayLength; i++)
		{	System.out.println (carray[i] + " = " + (int)carray[i]);
			occurrences[(int)carray[i]]++;
		}
		
		for(i = 0; i< occurrences.length; i++)  // start at 1 to remove NULL(EOF)
		{	if(occurrences[i] != 0)
			{	float percent = (float)occurrences[i] / carrayLength;
				System.out.println ((char)i + "("+i+") = " + occurrences[i] + ", % = " + percent);
				
				entropy += percent * (Math.log(percent)/Math.log(2));
			}
		}
		entropy = entropy * -1;
		
		System.out.println ("Entropy for the text file is " + entropy);
	
		
		/* Close all relevant files */ 
		io.done(); 
		
	}
	catch(ArrayIndexOutOfBoundsException aE)
	{	System.out.println("Thrown to indicate that an array has been accessed with an illegal index." + aE.getMessage());
	}
	
}// end of main


} // end class Entropy