Skip to content

Instantly share code, notes, and snippets.

@EmanueleTinari
Created May 17, 2021 12:39
Show Gist options
  • Save EmanueleTinari/b62cb6678f5e4e518596a23bd76ddfe4 to your computer and use it in GitHub Desktop.
Save EmanueleTinari/b62cb6678f5e4e518596a23bd76ddfe4 to your computer and use it in GitHub Desktop.
Funzioni ed utilità varie per Powershell.
<#
.Synopsis
Transform a decimal number into a Roman one and vice-versa.
.Description
Transform a decimal number in input, into its Roman version or
transform a Roman number in input, into its decimal value.
.Example
DecimalToRoman (Decimal_Number)
DecimalToRoman 10
Result: X
.Example
DecimalToRoman 1324
Result: MCCCXXIV
.Example
RomanToDecimal (Roman_Number)
RomanToDecimal VIII
Result: 8
.Example
RomanToDecimal MMXXI
Result: 2021
.Notes
Author : Emanuele Tinari (https://github.com/EmanueleTinari)
License: MS-PL (https://opensource.org/licenses/MS-PL)
Source : https://github.com/EmanueleTinari/EmanueleTinari
#>
function DecimalToRoman ($Decimal_Number)
{
if (($Decimal_Number -ge 5000) -or ($Decimal_Number -le 0))
{
return "Please enter a number between 1 and 4999"
}
$result = ""
# Associative array combining Roman numerals (name) and numerals (value)
$hash_roman_num =
@{
"M" = 1000
"CM" = 900
"D" = 500
"CD" = 400
"C" = 100
"XC" = 90
"L" = 50
"XL" = 40
"X" = 10
"IX" = 9
"V" = 5
"IV" = 4
"I" = 1
}
# Sort the associative array in ascending numerical order (value)
$hash_roman_num_sort = $hash_roman_num.GetEnumerator() |Sort-Object value -desc
foreach ($key_value in $hash_roman_num_sort)
{
$count = [math]::floor($Decimal_Number/$key_value.value)
$Decimal_Number = $Decimal_Number % $key_value.value
[string]$result += ($key_value.key -as [string]) * $count
}
return $result
}
function RomanToDecimal ($Roman_Number)
{
$t=@{I=1; IV=4; V=5; IX=9; X=10; XL=40; L=50; XC=90; C=100; CD=400; D=500; CM=900; M=1000}
1..$Roman_Number.Length | ForEach-Object{$x = $m = 0}{$i = $t[[string]$Roman_Number[–$_]];
if($i-lt$m) {$x-=$i} else {$x += $i; $m = $i}}{$x}
}
Export-ModuleMember -Function DecimalToRoman, RomanToDecimal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment