Skip to content

Instantly share code, notes, and snippets.

@rimas-kudelis
Last active December 29, 2017 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rimas-kudelis/07b19a37fea41186e9331651b15dd381 to your computer and use it in GitHub Desktop.
Save rimas-kudelis/07b19a37fea41186e9331651b15dd381 to your computer and use it in GitHub Desktop.
Arabic to Roman numerals converter
<?php
namespace App;
/**
* Converts positive decimal numbers to Roman numerals.
* Note: M (1000) is the largest Roman numeral supported by this function.
*/
class Converter
{
protected $mappings = [
[ 'I', 'V', 'X' ],
[ 'X', 'L', 'C' ],
[ 'C', 'D', 'M' ],
//[ 'M', 'ↁ', 'ↂ'],
];
function digit($num, $mapping)
{
if ($num <= 3) {
return str_repeat($mapping[0], $num);
}
if ($num == 4) {
return $mapping[0] . $mapping[1];
}
if ($num <= 8) {
return $mapping[1] . str_repeat($mapping[0], $num - 5);
}
// if $num === 9
return $mapping[0] . $mapping[2];
}
function convert($number) {
$numString = "$number";
$roman = '';
$mappings = $this->mappings;
while(strlen($numString) > 0 && !empty($mappings)) {
$digit = substr($numString, -1);
$numString = substr($numString, 0, -1);
$currentMapping = array_shift($mappings);
$roman = $this->digit((int)$digit, $currentMapping) . $roman;
}
$roman = str_repeat($currentMapping[2], (int)$numString) . $roman;
return $roman;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment