Skip to content

Instantly share code, notes, and snippets.

@robballou
Created February 16, 2012 03:56
Show Gist options
  • Save robballou/1841822 to your computer and use it in GitHub Desktop.
Save robballou/1841822 to your computer and use it in GitHub Desktop.
<?php
/*
Based on rules from http://en.wikipedia.org/wiki/Roman_numerals
*/
function romanToInt($roman){
$int = 0;
$characters = str_split($roman);
$previous = null;
$values = array('I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000);
foreach($characters as $character){
// default of adding this characters value to current value
$newValue = $int + $values[$character];
// if the previous value is a "subtraction" case, we'll need to adjust accordingly
if($previous == 'I' && in_array($character, array('V', 'X'))){
// subtract 1, add adj value
$newValue = ($int - 1) + $values[$character] - 1;
}
elseif($previous == 'X' && in_array($character, array('L', 'C'))){
// subtract 10, add adj value
$newValue = ($int - 10) + $values[$character] - 10;
}
elseif($previous == 'C' && in_array($character, array('D', 'M'))){
// subtract 100, add adj value
$newValue = ($int - 100) + $values[$character] - 100;
}
// set the new value and continue
$int = $newValue;
$previous = $character;
}
return $int;
}
/*
to read from a file:
$data = file('roman.txt');
foreach($data as $line){ echo romanToInt($line); }
*/
// test it!
$inputs = array(
'X',
'C',
'V',
'I',
'L',
'D',
'M',
'IX',
'III',
'IV',
'XC',
'MM',
'MDCCCCX',
'MCMLIV',
'MCMXC'
);
$answers = array(
10,
100,
5,
1,
50,
500,
1000,
9,
3,
4,
90,
2000,
1910,
1954,
1990
);
for($i=0; $i<count($inputs); $i++){
if(romanToInt($inputs[$i]) != $answers[$i]){
print "Failed: ". $inputs[$i] ." != ". $answers[$i] ."; received ". romanToInt($inputs[$i]) ."\n";
}
else {
print "Success! ". $inputs[$i] ." == ". $answers[$i] ."\n";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment