Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

/* Mohamed Anis MEKKI - 2003 (c) */ public class code { symbol symbols[]; String codes[]; int length; public code(source s) { this.length = s.length; this.symbols = s.symbols; this.codes = new String[1000]; int i=0; while (i < s.length) { (this.codes)[i] = ""; i++; } } public double lmoy() { double result = 0.0; int i = 0; while ( (i < symbols.length) && (symbols[i] != null) ) { result = result + ((symbols[i].prob)*(codes[i].length())); i++; } return(result); } public double lmin() { double result = 0.0; int i = 0; while ( (i < symbols.length) && (symbols[i] != null) ) { result = result - ((symbols[i].prob)*Math.log((symbols[i].prob))); i++; } result = result / Math.log(2); return(result); } public double rendement() { return(lmin()/lmoy()); } public void show() { int i=0; while (i < this.length) { ((this.symbols)[i]).show(); System.out.println("Code : "+(this.codes)[i]); i++; } } public void encode(String s,int c) { int i=0; int j=0; s=s+"-"; int l = s.length()/2; String str[] = new String[l]; while ( s.length() > 0 ) { str[j]=""; while ( s.charAt(i) != '-' ) { str[j] = str[j]+s.charAt(i); i++; } s = s.substring(i+1); i=0; j++; } j=0; while ( j < str.length ) { i=0; while ( i < this.length ) { if ( (((this.symbols)[i]).symb).equals(str[j]) ) { this.codes[i]=c+this.codes[i]; } i++; } j++; } } public tree hauffman() { int i= this.length; int j=0; tree tree_result[] = new tree[i]; tree result = new tree(null,null,null); tree permut = new tree(null,null,null); while ( j < i ) { tree_result[j] = new tree((this.symbols)[j],null,null); j++; } while ( i > 1 ) { this.encode(((tree_result[i-1]).root).symb,1); this.encode(((tree_result[i-2]).root).symb,0); permut = tree_result[i-2]; tree_result[i-2] = new tree((permut.root).add((tree_result[i-1]).root),tree_result[i-1],permut); i--; tree_result = tree.classify_tree_up(tree_result,i); } result = tree_result[0]; return(result); } public static void main(String args[]) { source M = new source(); source M2 = new source(); source M3 = new source(); source M4 = new source(); symbol a1 = new symbol("A1",0.8); symbol a2 = new symbol("A2",0.2); symbol a3 = new symbol("A3",0.1); //symbol a3 = new symbol("c",0.1); M.add_symbol(a1); M.add_symbol(a2); //M.add_symbol(a3); M2 = M.extend2(); M2.classify_up(); M3 = M2.extend2(); M3.classify_up(); M4 = M3.extend2(); M4.classify_up(); code c = new code(M4); tree hauffman_tree = c.hauffman(); hauffman_tree.show(); c.show(); System.out.println(" lmin : "+c.lmin()); System.out.println(" lmoy : "+c.lmoy()); System.out.println("rendement : "+c.rendement()); } }