sandeshMC

37 symbols and probability

Feb 19th, 2014
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.*;
  4. public class Compress {
  5.     public static void main(String[] args) {
  6.         Scanner sc=new Scanner(System.in);
  7.         String text="";
  8.         try {
  9.             text = new Scanner( new File("testdata.txt"), "UTF-8" ).useDelimiter("\\A").next();
  10.             System.out.println(text+"");
  11.         } catch (FileNotFoundException e) {
  12.             e.printStackTrace();
  13.         }
  14.         char ch[] = new char[37];
  15.         for(int i=0;i<10;i++)
  16.             ch[i]=(char)(i+48);
  17.         for(int i=0;i<26;i++)
  18.             ch[i+10]=(char)(i+65);
  19.         ch[36]=(char)32;
  20.         System.out.println("CHARACTERS IN THE TEXT FILE ARE : \n"+Arrays.toString(ch));
  21.         int count[] = new int[37];
  22.         for(int j=0;j<37;j++) {
  23.         for(int i=0;i<text.length();i++) {
  24.             if(ch[j]==text.charAt(i))
  25.                 count[j]=count[j]+1;
  26.         }
  27.         }
  28.         double d=text.length();
  29.         System.out.println("THE COUNT OF EACH CHARACTER IS : \n"+Arrays.toString(count));
  30.         System.out.println("TOTAL NO. OF CHARACTERS : "+text.length());
  31.         for(int i=0;i<count.length;i++) {
  32.             System.out.println("THE PROBABLITY OF "+ch[i]+" IS "+(count[i]/d));
  33.         }
  34.         double entropy=0.0;
  35.         for(int i=0;i<37;i++) {
  36.             if(count[i]==0)
  37.                 continue;
  38.             double probability=count[i]/d;         
  39.             double entropy1=probability*(Math.log(probability)/Math.log(2));
  40.             entropy+=entropy1;
  41.  
  42.         }
  43.         System.out.println("THE ENTROPY IS "+(-1)*entropy);
  44.        
  45.     }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment