# Re: [PHP-DB] Re: Now, how about Roman Numerals?

```"George Pitcher" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> That's great, but what about the reverse: Roman to Arabic?
>
> George in Oxford```
```

// NOTE: the order of the table is
// important! I will use greedy parsing,
// so (for example) IX and IV must precede
// I to parse correctly.
\$RomanTable = array(
"M" => 1000,
"CM" => 900,
"D" => 500,
"CD" => 400,
"C" => 100,
"XC" => 90,
"L" => 50,
"XL" => 40,
"X" => 10,
"IX" => 9,
"V" => 5,
"IV" => 4,
"I" => 1
);

function MatchClause(\$needle, \$haystack) {
// These two tests are probably just paranoia,
// but - hey, I'm paranoid. ;-)
if (strlen(\$haystack) < 1)
return false;
if (strlen(\$haystack) < strlen(\$needle))
return false;

return( strncasecmp(\$needle, \$haystack, strlen(\$needle)) == 0 );
}

function RemoveClause(\$needle, \$haystack) {
return( substr(\$haystack, strlen(\$needle)) );
}

function RomanToInt(\$str) {
global \$RomanTable;
\$sum = 0;

do
{
\$done = true;

foreach(\$RomanTable as \$clause => \$value)
if ( MatchClause(\$clause, \$str) ) {
\$sum += \$value;
\$str = RemoveClause(\$clause, \$str);

\$done = false;
break;
}
}
while (\$done == false);

return(\$sum);
}

NOTE!  This algorithm is sufficient but not complete -
it will correctly translate all legal Roman-numeral strings,
but cannot detect illegal strings.

--
Hugh Bothwell     [EMAIL PROTECTED]     Kingston ON Canada
v3.1 GCS/E/AT d- s+: a- C+++ L++>+++\$ P+ E- W+++\$ N++ K? w++ M PS+
PE++ Y+ PGP+ t-- 5++ !X R+ tv b++++ DI+++ D-(++) G+ e(++) h-- r- y+

--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

```