Robson » Little Red Book » Roman to arabic

Chapter 9 - Question 1

Design a program that accepts an input sequence representing a roman number and outputs its arabic decimal equivilant.

Solution 1

This is a fairly simple question. It took me longer to work out how to generate a random roman number than convert it to arabic!

The solution doesn't have much erorr checking, but it will work fine with a valid roman number.

<?
 
   // these are arabic numbers and their roman equivilant
   $arabic_roman = array(
                   1   => 'I', 5   => 'V', 10   => 'X', 50 => 'L',
                   100 => 'C', 500 => 'D', 1000 => 'M'
                       );
                       
   // ** generate roman number
                       
   // store all the roman numerals in an array                    
   $symbols = array_values(array_reverse($arabic_roman));
   // loop through each roman symbol
   foreach($symbols as $symbol)
       // add none or one of that symbol to the roman number
       $roman .= str_repeat($symbol, mt_rand(0, 1));
   // if it's empty
   if (!$roman)
       // just use one    
       $roman = 'I';
 
   // ** convert to arabic
                       
   // loop through all the letters in the roman number
   for ($n = 0; $n < strlen($roman); $n++)
   {
       // check if this is a one
       // this isn't the end
       // the next character isn't also a one
       if ($roman[$n] == 'I' && $n <> strlen($roman)-1 && $roman[$n+1] <> 'I')
           // skip this and add the next minus one
           $number = array_search($roman[++$n], $arabic_roman)-1;
       else
           // get the arabic equvilant
           $number = array_search($roman[$n], $arabic_roman);
       // add the current number to the running total    
       $total += $number;
   }
   
   // display the original roman number and its arabic equivilant
   echo 'The roman number ' . $roman . ' is ' . $total . ' in arabic';
   
?>

Which produces:

The roman number MDCVI is 1606 in arabic

Log

© 2004-17 robson | cc unless stated