Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roman Numeral to integer function

basically i am trying to create a function that will turn a Roman numeral into a integer.

I have an array:

$roman_numerals=[
    '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
];

I'm fairly new to PHP so i'm still getting used to the way of think so please bear in mind i'm still learning :)

here is my function - or what i have so far:

//Array
function romanToInteger($key)
{
$roman_numerals=[
    '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
];

$roman = intval($key);
$result = 0;

foreach ($roman_numerals as $key => $value) {
    while (strpos($roman, $key) === 0) {
        $result += $value;
        $roman = substr($roman, strlen($key));
    }
}
var_dump($roman); //test
echo $result;
}

i have been at this for hours and would just like the see the light of it, any advice would be greatly appreciated.

when i run it in the command line with

echo romanToInteger('I');

i just get returned 0 and i think its something to do with my intval?

Sorry again for being a noob, help appreciated though or any pointers! :)

like image 480
Kolvin Avatar asked May 13 '15 14:05

Kolvin


1 Answers

Yes it has something to do with the intval.

You're basically casting your roman input into an integer rendering it into 0.

Remove that:

function romanToInteger($key)
{
    $romans = [
        '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,
    ];

    $roman = $key;
    $result = 0;

    foreach ($romans as $key => $value) {
        while (strpos($roman, $key) === 0) {
            $result += $value;
            $roman = substr($roman, strlen($key));
        }
    }
    echo $result;
}

romanToInteger('IV');

Sample Output

like image 79
Kevin Avatar answered Sep 28 '22 20:09

Kevin