Functions
WebDev/*nix assorted functions & hacks
Search
find all
Array
-
Bash
-
Classes
-
Config
-
DateTime
-
Debug
-
dotjs
-
File
-
foooo
-
Git
-
HTML
-
Images
-
Javascript
-
Linux
-
Math
-
Misc
-
MySQL
-
OS X
-
Reading
-
Redis
-
Shell scripts
-
snippets
-
SQL
-
Strings
-
TextMate
-
Web
-
\(^o^)/ Fun!
-
_Misc hacks
-
_Pages
Math
rom2num($string)
1
found
auth
Name:
Category: Math
Body:
/* incomplete, still allows invalid input, but works with valid input. it was an end-of-the-day-for-fun attempt, inspired by the Python exercises.. eh. *shrug* (Python solution beat the crap out of the below in elegance, naturally) */ function rom2num($string) { $numerals = array('I'=>1, 'V'=>5, 'X'=>10, 'L'=>50, 'C'=>100, 'D'=>500, 'M'=>1000); $keys = array_keys($numerals); $out = 0; $sk = 0; # smallest key index (out of keys) for ($i=strlen($string)-1; $i >= 0; $i--) { $char = substr($string, $i, 1); $nextsmaller = (array_search($string[$i-1], $keys) < array_search($char, $keys)); if ($i > 0 && $nextsmaller) { $next = $string[$i-1]; if (in_array($next, array('I', 'X', 'C'))) { if (in_array(array_search($char, $keys)-array_search($next, $keys), array(1, 2))) { $add = $numerals[$char] - $numerals[$next]; $i--; $sk = array_search($char, $keys); }else{ echo "Failed 3"; return false; } }else{ echo "Failed 2"; return false; } }else{ if (array_search($char, $keys) < $sk) { echo "Failed 1"; return false; } $sk = array_search($char, $keys); $add = $numerals[$char]; } $out += $add; } return $out; }
Footer