Hello, I am an Engineering Manager at Facebook with 13+ years in Ad Technology, Natural Language Processing and Data mining. (Learn More)
by Pravin Paratey

Limerick Generator - Part I

Synopsis

The following code demonstrates an alien limerick generator. Alien because it does not generate meaningful words. In part II, we will see how to add meaningful words.

Code

You can view the code and see it in action here.

<?php
    /// Generates a word with $num_consonants number of consonants
    /// ex. $num_consonants = 3 will produce words like:
    /// - diwali
    /// - beaten
    function generate_word($num_consonants)
    {
        $output = ""; // Return variable
        $vowels = array('a', 'e', 'i', 'o', 'u');
       
        for($i = 0; $i < $num_consonants; $i++)
        {
            // Pick a random character and a vowel
            $char = 98;
            do
            {
                $char = rand(98, 122); // b - z
            }
            while($char == 101 || $char == 105 || $char == 111 || $char == 117);
            $vowel_selector = rand(0, 4);
           
            // At this point, we've got char and a vowel
            // Now we decide which one goes first
            $toss = rand(0, 1);
            if ($toss == 1)
            {
                $output = $output . chr($char) . $vowels[$vowel_selector];
            }
            else
            {
                $output = $output . $vowels[$vowel_selector] . chr($char);
            }
        }
       
        return $output;
    }

    /// Generates a sentence with $num_words number of words
    function generate_sentence($num_words)
    {
        $output = '';
        for($i = 0; $i < $num_words; $i++)
        {
            $output = $output . generate_word(rand(1,3)) . ' ';
        }
       
        return $output;
    }
   
   
    /// Replaces the last two characters of $sentence with $suffix
    function replace_sentence($sentence, $suffix)
    {
        return substr($sentence, 0, strlen($sentence) - 2) . $suffix;
    }

    /// Returns a randomly generated alien limerick
    function generate_limerick()
    {
        $first_line = generate_sentence(6);
        $suffix = substr($first_line, strlen($first_line) - 3);
       
        $second_line = replace_sentence(generate_sentence(6), $suffix);
        $fifth_line = replace_sentence(generate_sentence(6), $suffix);
       
        $third_line = generate_sentence(3);
        $suffix = substr($third_line, strlen($third_line) - 3);
        $fourth_line = replace_sentence(generate_sentence(3), $suffix);
       
        $output = $first_line . '<br />' .
            $second_line . '<br />' .
            $third_line . '<br />' .
            $fourth_line . '<br />' .
            $fifth_line . '<br />';
           
        return $output;
    }
?>

Sample Output

orraxa iz hoxori upifoc awhapo ed ceva ovat ujbazo arli du caded uc iqek suenvo zaek ammiip edbeuvo moix beak kuefyo irogno iluyox xoiqged