Last active
December 13, 2017 15:39
-
-
Save groovili/93dbec69522fbfcbb31e505bb0cb0502 to your computer and use it in GitHub Desktop.
CLI script to convert integer to roman number
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 | |
function getPeriod(int $int, int $n): int { | |
$m = '1'; | |
$m .= str_repeat(0, $n); | |
return $int * ((int) $m); | |
} | |
function getRomanNumber(int $input): string{ | |
$codes = [ | |
1 => 'I', | |
4 => 'IV', | |
5 => 'V', | |
9 => 'IX', | |
10 => 'X', | |
40 => 'XL', | |
50 => 'L', | |
90 => 'XC', | |
100 => 'C', | |
400 => 'CD', | |
500 => 'D', | |
900 => 'CM', | |
1000 => 'M', | |
]; | |
$result = ''; | |
if (1 > $input){ | |
return $result; | |
} | |
foreach (array_reverse($codes, true) as $key => $romanNumber){ | |
$d = $input/$key; | |
if ($d == 1){ | |
$result .= $romanNumber; | |
break; | |
} | |
if ($d > 1 && $input%$key !== 0){ | |
$result .= $romanNumber; | |
$result .= getRomanNumber($input%$key); | |
break; | |
} | |
if ($d > 1 && $input%$key === 0){ | |
$result .= str_repeat($romanNumber,$input/$key); | |
break; | |
} | |
} | |
return $result; | |
} | |
function solution(int $number): string { | |
if (!is_int($number) || 0 >= $number) return false; | |
$numStr = (string) $number; | |
$len = strlen($numStr); | |
$result = ''; | |
for ($i = 0; $i < $len; $i++){ | |
$s = (int) $numStr[$i]; | |
$result .= getRomanNumber(getPeriod($s, ($len - $i - 1))); | |
} | |
return $result; | |
} | |
$handle = fopen ('php://stdin','r'); | |
while (1) { | |
echo "Input integer to convert:\n"; | |
$arg = fgets($handle); | |
if ($arg === 'exit'){ | |
echo "Bye bye\n"; | |
die; | |
} | |
$num = (int) $arg; | |
if (!is_numeric($num)){ | |
echo "Input should be numeric!\n"; | |
continue; | |
} | |
echo solution($num) . "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment