Last active
April 16, 2024 12:21
-
-
Save ronssij/f30a5976eda9fa1eb6e330b7c1c2e57b to your computer and use it in GitHub Desktop.
Laravel collection roman numeral conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$roman = ['i' => 1, 'v' => 5, 'x' => 10, 'l' => 50, 'c' => 100, 'd' => 500, 'm' => 1000]; | |
$value = 'IX'; | |
$result = 0; | |
$prevValue = 0; | |
if (preg_match('/[^ivxlcdm]|i{4,}|x{4,}|c{4,}|m{4,}|v{2,}|l{2,}|d{2,}/i', $value)) { | |
return "invalid format"; | |
} | |
return str($value)->ucsplit('') | |
->reverse() | |
->values() | |
->map(fn ($item) => $roman[strtolower($item)]) | |
->reduce(function ($carry, $item) use (&$prevValue) { | |
$result = ($item >= $prevValue) ? $carry + $item : $carry - $item; | |
$prevValue = $item; | |
return $result; | |
}, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment