/* Roman numerals/Decode in Picat. From Rosetta code: http://rosettacode.org/wiki/Roman_numerals/Decode """ Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order. """ Model created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ % import util. main => go. go => List = ["IV", "XLII", "M", "MCXI", "CMXI", "MCM", "MCMXC", "MMVIII", "MMIX", "MCDXLIV", "MDCLXVI", "MMXII"], foreach(R in List) printf("%-8s: %w\n", R, roman_decode(R)) end, nl. roman_decode(Str) = Res => if Str == "" then Res := "" else D = new_map(findall((R=D), roman(R,D))), Res = 0, Old = 0, foreach(S in Str) N = D.get(S), % Fix for the Roman convention that XC = 90, not 110. if Old > 0, N > Old then Res := Res - 2*Old end, Res := Res + N, Old := N end end. roman('I', 1). roman('V', 5). roman('X', 10). roman('L', 50). roman('C', 100). roman('D', 500). roman('M', 1000).