Markov Chain Generator


/ Published in: Perl
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.