Robson » Little Red Book » Lexicographical order

Chapter 6 - Question 16

Given two character arrays (or strings), each contaning only letters A..Z or spaces, and thus holding words, produce a program that determines whether or not the first word would preceed the second, in a dictionary.

Solution 1

Most of the problems towards the end of this chapter are very simple to complete in PHP. This one isn't an exception.

<?
   // generates random strings of nonsense
   function random_string()
   {
       // random number of letters
       for ($n = 0; $n < mt_rand(20, 40); $n++)
       {
           // if this isn't the first character
           // if the last character isn't a space
           // If there's a small chance
           if ($n <> 0 && substr($string, $n-1, 1) <> ' ' && mt_rand(1, 3) == 1)
               // concatenate a space
               $string .= ' ';
           else
               // otherwise, add a random letter
               $string .= chr(ord('A') + mt_rand(0, 25));
       }    
       return $string;
   }
 
   // create two strings
   $string1 = random_string();
   $string2 = random_string();
 
   // show both strings
   echo $string1 . '<br/>' . $string2;
   // show which would appear first
   echo '<br/>String ' . (2-($string1 < $string2)) . ' would appear first.';
?>

Which produces:

LEXABRG H PU YYYAQ HZ FN HW
ZFCMYW I XDD XZ JB TV
String 1 would appear first.

Log

© 2004-17 robson | cc unless stated