From 5714e72939a01772deb77cfabf19061b2f5bc4de Mon Sep 17 00:00:00 2001 From: Noah Hellman Date: Mon, 23 Jan 2023 22:22:23 +0100 Subject: [PATCH] parser: parse roman numerals --- src/lib.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3494cd9..70a23c6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -287,8 +287,32 @@ impl OrderedListNumbering { .map(|(d, w)| w * (d - d0 + 1)) .sum() } - Self::RomanLower => 1, - Self::RomanUpper => 1, + Self::RomanLower | Self::RomanUpper => { + fn value(d: char) -> u32 { + match d { + 'i' | 'I' => 1, + 'v' | 'V' => 5, + 'x' | 'X' => 10, + 'l' | 'L' => 50, + 'c' | 'C' => 100, + 'd' | 'D' => 500, + 'm' | 'M' => 1000, + _ => panic!(), + } + } + let mut prev = 0; + let mut sum = 0; + for d in n.chars().rev() { + let v = value(d); + if v < prev { + sum -= v; + } else { + sum += v; + } + prev = v; + } + sum + } } } }