Skip to content

Instantly share code, notes, and snippets.

@archenemy
Last active August 29, 2015 14:10
Show Gist options
  • Save archenemy/80ed85410df39e33d3d1 to your computer and use it in GitHub Desktop.
Save archenemy/80ed85410df39e33d3d1 to your computer and use it in GitHub Desktop.
<?php
$stdin = fopen ("php://stdin","r");
$brain = array();
print "> ";
while ( $line = trim(fgets($stdin)) ) {
if ( $line == "q" ) break;
// break into words array
$words = explode(" ", $line);
// if we dont have at least 2 words (one chain) skip for input
if ( count($words) < 2 ) continue;
/////////////
// Train the Markov Brain with this new sentence chain
// pop off the first word
$word = $words[0];
// this loop treads the sentence as a chain of words, where $word -> $next_word
for ( $i=1; $i < count($words); $i++ ) {
$next_word = $words[$i];
// if our marky bot hasn't experienced this word yet, initialize it's array
if ( ! array_key_exists($word, $brain) ) $brain[$word] = array();
// learn the word!
$brain[$word][] = $next_word;
$word = $next_word;
}
// This part adds an "end of sentence" marker. We treat it kind of like a word.
if ( ! array_key_exists($word, $brain) ) $brain[$word] = array();
$brain[$word][] = ".";
print_r($brain);
////////////
// Generate a Markov Chain based on a random word from the sentence
$word = $words[array_rand($words)];
$chain = array();
while ( $word != "." ) {
// Pull a random word out of the list of words our Marky bot has seen follow our given word
// in the past. We know $brain[$word] will always exist because we create everything in $words
// in the learning phase.
print "\$word = $word\n";
if (!array_key_exists($word,$brain)) exit;
$possible_next_words = $brain[$word];
$word = $possible_next_words[array_rand($possible_next_words)];
print "chosen word: $word\n";
$chain[] = $word;
}
print "marky > " . implode(" ", $chain) . "\n";
print "> ";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment