Jumpi’s Notepad

My annotations about the life, universe and everything!!! ;)

Posts Tagged ‘markov

The Practice of Perl II

with one comment

Upon requesting made and continuing my posts about perl practicality, show here a very elaborated code, extract from classic book that I have reading again, Pike & Kerninghan Practice of Programming.

Yes, this book have a very interesting example of Markov Chains in perl.

For those that dont knowing about Markov Chains, this is a particular case in stochastic process, where previous states are irrelevant for prediction of following states, since that actual state is knowing. This technique is very used for generate random text, as in the book example, but, the author uses only cases that envolve two-word prefixes, for test effects.

The code used in the example, written in perl language:

$MAXGEN = 10000;
$NONWORD = “\n”;
$wl = $w2 = $NONWORD;
while (<>) {
foreach (split) {
push(@{$statetab{$w1}{$w2}}, $_);
($w1, $w2) = ($w2, $_);
push(@($statetab{$w1}{$w2}}, $NONWORD);
$w1 = $w2 = $NONWORD;
for ($i = 0; $i < $MAXGEN; $i++) {
$suf = $statetab{$w1}{$w2};
$r = int(rand @$suf);
exit if(($t = $suf->[$r]) eq $NONWORD);
print “$t\n”;
($w1, $w2) = ($w2, $t);

And more impressive is what the result is make of simple and rapid form, very rapid, in the final of chapter has a performance table where perl losing only for C implementation, other implementations are written in Java, C++/STL/Deque, C++/STL/List and AWK, being that have 150 lines of code in C versus only 18 in perl.

Well, I dont make apologies to perl, because I love C too, but, as the author says and define in the final of paragraph, scripting languages (perl, in this case) are a good choice for experimental programming and making prototypes, and I conclude, for rapid tasks and tests, perl is again language of my choice.

Written by jumpi

January 6, 2008 at 8:43 pm

Posted in english, Programming

Tagged with , , , ,