Friday, February 13, 2009

Brian Writes an e e cummings Poem... Using Recursion

The Algorithm:

function processEEPoem($words,$str){
if (count($words['objects'])<=1||strlen($str)>1000) {
return $str;
} else {
if (strlen($str)>20) $str = $str."
\n";
$key = array_rand($words,3);
$val = $words[ $key[0] ][ rand(0,count($words[ $key[0] ])-1) ];
$val2 = $words[ $key[1] ][ rand(0,count($words[ $key[1] ])-1) ];
$val3 = $words[ $key[2] ][ rand(0,count($words[ $key[2] ])-1) ];
$rand = rand(0,3);
switch( $rand ) {
case 0: $str .= "$val $val2 $val3 ";
case 1: $str .= "($val)$val2$val3";
case 2: $str .= "$val-$val3 ";
default: $str .= substr($val,0,2).", $val2 ";
}
if (rand(0,3)==0) $str .= "?";
unset($words['objects'][rand(0,count($words['objects'])-1)]);
unset($words['objects'][rand(0,count($words['objects'])-1)]);
return processEEPoem($words,$str);
}
}
$initWords['pronouns'] = array("thy","thee","o","mine","thou");
$initWords['verbs'] = array("pinched","poked","sprung","prodded","conceived","squeezed");
$initWords['adjectives'] = array("sweet","naughty","mighty","scraggy","rhythmic","spontaneous");
$initWords['objects'] = array("lover","fingers","death","gods","beauty","thumb");
echo processEEPoem( $initWords,"" );

and the results...

mighty rhythmic poked poked fingers prodded

(mine)fingerssweetmine-sweet mi, fingers
sprung thee lover (sprung)theeloversprung-lover sp, thee
th, squeezed ?
mine-scraggy mi, squeezed
thee pinched (thee)pinchedthee- th, pinched
prodded-thee pr,
-prodded , o ?
mighty thee (mighty)theemighty- mi, thee
, thy
pinched-thee pi,
thee rhythmic (thee)rhythmicthee- th, rhythmic
, poked
scraggy-prodded sc,
sweet- sw, thy
()sweetsqueezed-squeezed , sweet
th, pinched ?
thou poked sweet (thou)pokedsweetthou-sweet th, poked
th, ?
, sweet
o, squeezed
sprung mighty (sprung)mightysprung- sp, mighty
-conceived , o ?
thee-sweet th, prodded ?
scraggy conceived (scraggy)conceivedscraggy-conceived sc,
o, pinched
o-naughty o, pinched
thee rhythmic (thee)rhythmicthee- th, rhythmic
(thee)sprungthee- th, sprung
(thee)sweetthee- th, sweet
sp, mine
pinched thee ()pinchedthee-thee , pinched



try it out here!

1 comment:

skinny bones said...

this is the coolest thing i've seen in a while.