Guest User

Untitled

a guest
Jun 22nd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. <?php
  2.  
  3. class Markov {
  4. protected $words = array();
  5. protected $cache = array();
  6.  
  7. public function compile($source) {
  8. preg_match_all('([^\s(){}\[\]]+)', $source, $words);
  9.  
  10. $words = $words[0];
  11. $length = count($words) - 3;
  12. $sets = array(); $progress = 0;
  13.  
  14. while ($progress < $length) {
  15. $count = 0; $set = array();
  16.  
  17. while ($count < 3) {
  18. $set[] = $words[$progress + $count]; $count++;
  19. }
  20.  
  21. $sets[] = $set; $progress++;
  22. }
  23.  
  24. foreach ($sets as $key) {
  25. $value = array_pop($key);
  26. $key = implode(' ', $key);
  27.  
  28. if (isset($this->cache[$key])) {
  29. $this->cache[$key][] = $value;
  30. }
  31.  
  32. else {
  33. $this->cache[$key] = array($value);
  34. }
  35. }
  36.  
  37. $this->words = $words;
  38. }
  39.  
  40. public function generate($length) {
  41. $index = $this->chooseFirst();
  42. $word_a = $this->words[$index];
  43. $word_b = $this->words[$index + 1];
  44. $count = 0; $size = $length * 8;
  45. $output = array();
  46.  
  47. while ($count++ < $size) {
  48. $output[] = $word_a;
  49.  
  50. if (preg_match('/[.!?]$/', $word_a)) {
  51. if (count($output) > $length) break;
  52.  
  53. $index = $this->chooseFirst();
  54. $word_a = $this->words[$index];
  55. $word_b = $this->words[$index + 1];
  56. }
  57.  
  58. else {
  59. $cache = $this->cache["{$word_a} {$word_b}"];
  60. $word_c = $cache[array_rand($cache)];
  61. $word_a = $word_b;
  62. $word_b = $word_c;
  63. }
  64. }
  65.  
  66. return $output;
  67. }
  68.  
  69. public function chooseFirst() {
  70. $choices = array();
  71.  
  72. foreach ($this->words as $index => $word) {
  73. if (preg_match('/^[A-Z].*[^.!?]$/', $word)) {
  74. $choices[] = $index;
  75. }
  76. }
  77.  
  78. return $choices[array_rand($choices)];
  79. }
  80. }
  81.  
  82. $markov = new Markov(3);
  83. $markov->compile(file_get_contents('./markov3.txt'));
  84. $words = $markov->generate(100);
  85.  
  86. echo '<p style="width: 30em;">', implode(' ', $words), '</p>';
  87.  
  88. ?>
Add Comment
Please, Sign In to add comment