We Recommend

Learning Perl Learning Perl
In this smooth, carefully paced course, a leading Perl trainer teaches you to program in the language that threatens to make C, sed, awk, and the Unix shell obsolete for many tasks. This book is the "official" guide for both formal (classroom) and informal learning. It is fully accessible to the novice programmer.


Posted By

rengber on 06/30/08


Tagged

fun Interesting Learn


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

romanos


Markov Chain Generator


Published in: Perl 


URL: http://www.beetleinabox.com/markov.html

My PERL isn't strong enough to get this yet, but I plan on porting to C#.

Read this: http://en.wikipedia.org/wiki/Markov_chain

  1. # Copyright (C) 1999 Lucent Technologies
  2. # Excerpted from 'The Practice of Programming'
  3. # by Brian W. Kernighan and Rob Pike
  4.  
  5. # markov.pl: markov chain algorithm for 2-word prefixes
  6.  
  7. $MAXGEN = 10000;
  8. $NONWORD = "\n";
  9. $w1 = $w2 = $NONWORD; # initial state
  10. while (<>)
  11. { # read each line of input
  12. foreach (split)
  13. {
  14. push(@{$statetab{$w1}{$w2}}, $_);
  15. ($w1, $w2) = ($w2, $_); # multiple assignment
  16. }
  17. }
  18.  
  19. push(@{$statetab{$w1}{$w2}}, $NONWORD); # add tail
  20. $w1 = $w2 = $NONWORD;
  21.  
  22. for ($i = 0; $i < $MAXGEN; $i++)
  23. {
  24. $suf = $statetab{$w1}{$w2}; # array reference
  25. $r = int(rand @$suf); # @$suf is number of elems
  26. exit if (($t = $suf->[$r]) eq $NONWORD);
  27. print "$t\n";
  28. ($w1, $w2) = ($w2, $t); # advance chain
  29. }

Report this snippet 

You need to login to post a comment.