RosettaCodeData/Task/Roman-numerals-Decode/D/roman-numerals-decode-1.d

20 lines
614 B
D
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
import std.regex, std.algorithm;
int toArabic(in string s) /*pure nothrow*/ {
static immutable weights = [1000, 900, 500, 400, 100,
90, 50, 40, 10, 9, 5, 4, 1];
static immutable symbols = ["M","CM","D","CD","C","XC",
"L","XL","X","IX","V","IV","I"];
int arabic;
2013-10-27 22:24:23 +00:00
foreach (m; s.matchAll("CM|CD|XC|XL|IX|IV|[MDCLXVI]".regex))
2013-04-10 23:57:08 -07:00
arabic += weights[symbols.countUntil(m.hit)];
return arabic;
}
void main() {
2013-10-27 22:24:23 +00:00
assert("MCMXC".toArabic == 1990);
assert("MMVIII".toArabic == 2008);
assert("MDCLXVI".toArabic == 1666);
2013-04-10 23:57:08 -07:00
}