#!/usr/local/bin/perl -w # # David MacKay Dec 97 # # frequency2.p - counts letters (both cases) and writes a huffman code # used to make huffman3.tcl # $verbose = 1 ; @a = <> ; # read in everything. $b = join ( '' , @a ) ; $b =~ s/[^a-zA-Z01-9]/ /g ; # turn all punctuation to space $b =~ s/\s+/_/g ; # turn all space to _ $row = 0 ; for $f ('a','b','c','d','e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z','_','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0') { $count = $b =~ s/$f//g; $count ++ ; print "$f : $count\n" ; $pr{$f} = $count ; $arr[$row] = $f ; # $code{$f} = "" ; $c[$row] = $count ; $row ++ ; } $M = $row ; if ( $verbose ) { print "omitted guff->" ; print $b,"<-\n" ; } # make huffman code # @sorted = sort bypr @arr ; print "sorted characters\n" ; print @sorted , "\n" ; sub bypr { $pr{$a} <=> $pr{$b} ; } print @c ; print "\n" ; # print $c[0],"\n" ; iterate ( $M ) ; # iterate makes the tree, now we need to deduce the # codewords. $codes[0] = "" ; for ( $mm = 2 ; $mm <= $M ; $mm ++ ) { $f = $ff[$mm] ; $s = $ss[$mm] ; $co = $codes[$f] ; # this is the one we will expand # move down everyone below s for ( $m = $mm - 1 ; $m > $s ; $m -- ) { $codes[$m] = $codes[$m-1] ; } $codes[$f] = $co."0" ; $codes[$s] = $co."1" ; } print " codewords : [\n" ; for ( $mm = 0 ; $mm < $M ; $mm ++ ) { # print $arr[$mm] , " " , $codes[$mm] , "\t\\\n" ; print $arr[$mm] , " " , $codes[$mm] , "\n" ; } print "]\n" ; # end sub bynumber { $a <=> $b; } sub iterate { #usage ( $m ) local ( $m ) = @_ ; print "entered iterate, m=$m\n" ; # print $c[0],"\n" ; print join ( ' ' , @c ) , "\n" ; # run through the array, finding the smallest two entries @sorted = sort bynumber @c[0..$m-1] ; $th = $sorted[ 1 ] ; for ( $mm = 0 , $found = 0 ; $mm < $m ; $mm ++ ) { if ( $c[$mm] <= $th ) { $first = $mm ; $found ++ ; last ; } } for ( $mm ++ ; $mm < $m ; $mm ++ ) { if ( $c[$mm] <= $th ) { $second = $mm ; $found ++ ; last ; } } if ( $found != 2 ) { print STDERR "warning didn't find 2 threshold = !\n" ; } # throw the weight of the 2nd into the 1st $c[$first] += $c[$second] ; # move everyone else up the list for ( $mm = $second ; $mm < $m-1 ; $mm ++ ) { $c[$mm] = $c[$mm+1] ; } $c[$mm] = "" ; # record what has been done $ff[$m] = $first ; $ss[$m] = $second ; print $first, " " , $second , "\n" ; if ( $m > 2 ) { iterate ( $m-1 , @c ) ; } }