1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
static ROMAN: [(char, i32); 7] = [
('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000) ];
static ROMAN_PAIRS: [(&'static str, i32); 13] = [
("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) ];
pub static MAX: i32 = 3999;
pub fn to(n: i32) -> Option<String> {
if n <= 0 || n > MAX { return None }
let mut out = String::new();
let mut n = n;
for &(name, value) in ROMAN_PAIRS.iter() {
while n >= value {
n -= value;
out.push_str(name);
}
}
assert!(n == 0);
Some(out)
}
#[test]
fn test_to_roman() {
let roman = "I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII";
for (i, x) in roman.split_whitespace().enumerate() {
let n = (i+1) as i32;
assert_eq!(to(n).unwrap(), x);
}
assert_eq!(to(1984).unwrap(), "MCMLXXXIV");
}
pub fn from(txt: &str) -> Option<i32> {
let n = match from_lax(txt) {
Some(n) => n,
None => return None
};
match to(n) {
Some(ref x) if *x == txt => Some(n),
_ => None
}
}
fn from_lax(txt: &str) -> Option<i32> {
let (mut n, mut max) = (0, 0);
for c in txt.chars().rev() {
let it = ROMAN.iter().find(|x| { let &(ch, _) = *x; ch == c } );
if it.is_none() { return None }
let &(_, val) = it.unwrap();
if val < max {
n -= val;
} else {
n += val;
max = val;
}
}
Some(n)
}
#[test]
fn test_from() {
assert!(from("i").is_none());
}
#[test]
fn test_to_from() {
for n in 1..MAX {
assert_eq!(from(&to(n).unwrap()).unwrap(), n);
}
}