Answers for "roman numerals using hashmap and struct"

0

roman numerals using hashmap and struct

// Roman numerals using hashmap and struct
struct RomanNumeral {
    symbol: &'static str,
    arabic: u32
}
 
const NUMERALS: [RomanNumeral; 13] = [
    RomanNumeral {symbol: "M",  arabic: 1000},
    RomanNumeral {symbol: "CM", arabic: 900},
    RomanNumeral {symbol: "D",  arabic: 500},
    RomanNumeral {symbol: "CD", arabic: 400},
    RomanNumeral {symbol: "C",  arabic: 100},
    RomanNumeral {symbol: "XC", arabic: 90},
    RomanNumeral {symbol: "L",  arabic: 50},
    RomanNumeral {symbol: "XL", arabic: 40},
    RomanNumeral {symbol: "X",  arabic: 10},
    RomanNumeral {symbol: "IX", arabic: 9},
    RomanNumeral {symbol: "V",  arabic: 5},
    RomanNumeral {symbol: "IV", arabic: 4},
    RomanNumeral {symbol: "I",  arabic: 1}
];
 
fn to_arabic(roman: &str) -> u32 {
    match NUMERALS.iter().find(|num| roman.starts_with(num.symbol)) {
        Some(num) => num.arabic + to_arabic(&roman[num.symbol.len()..]),
        None => 0, // if string empty, add nothing
    }
}
 
fn main() {
    let roms = ["MMXIV", "MCMXCIX", "XXV", "MDCLXVI", "MMMDCCCLXXXVIII"];
    for &r in &roms {
        // 15 is minimum formatting width of the first argument, there for alignment
        println!("{:2$} = {}", r, to_arabic(r), 15);
    }
}
Posted by: Guest on August-19-2021

Code answers related to "roman numerals using hashmap and struct"

Browse Popular Code Answers by Language