Skip to content

Instantly share code, notes, and snippets.

@ronssij
Last active April 16, 2024 12:21
Show Gist options
  • Save ronssij/f30a5976eda9fa1eb6e330b7c1c2e57b to your computer and use it in GitHub Desktop.
Save ronssij/f30a5976eda9fa1eb6e330b7c1c2e57b to your computer and use it in GitHub Desktop.
Laravel collection roman numeral conversion
<?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