PowerShell: Roman numerals
Puzzles on a Saturday morning!
This function takes a number and converts it to Roman numerals.
using namespace System.Collections.Generic
$number = 793
$bases = @(
@{ unit = "I"; five = "V"; next = "X" }
@{ unit = "X"; five = "L"; next = "C" }
@{ unit = "C"; five = "D"; next = "M" }
@{ unit = "M"; }
)
function roman ($number, $base) {
$unit = $bases[$base].unit
$five = $bases[$base].five
$next = $bases[$base].next
if ($number -in @(1..3)) {
$unit * $number
} elseif ($number -eq 4) {
$unit + $five
} elseif ($number -eq 5) {
$five
} elseif ($number -in @(6..8) ) {
$five + $unit * $($number - 5)
} elseif ($number -eq 9) {
$unit + $next
}
}
$charArray = $number.ToString().ToCharArray()
[array]::Reverse($charArray)
$result = [List[string]]::new()
for ($i = 0; $i -lt $charArray.Count; $i++) {
$base = $i
$string = [char]::ToString($charArray[$i])
$number = [int] $string
$roman = roman $number $base
$result.Add($roman)
}
$result.Reverse()
$result -join ""