Created
June 13, 2020 20:39
-
-
Save BrianKopp/44f42af80329ab121c7b3931d042a413 to your computer and use it in GitHub Desktop.
Programming Challenge - Rust - Roman Numerals Checkpoint 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
fn main() { | |
// get the command line argument | |
let args: Vec<String> = env::args().collect(); | |
// first command line arg is the program | |
if args.len() < 2 { | |
panic!("must supply a command line argument of the number to convert"); | |
} | |
// parse or fail | |
let i = args[1].parse::<i32>().expect("Unable to parse command line argument to int"); | |
// compute the roman numeral | |
let rn = make_roman_numeral(i); | |
println!("made roman numeral for {:?} - {:?}", i, rn); | |
} | |
// associate a roman numeral with its value | |
struct RomanNumeral { | |
txt: char, | |
value: i32, | |
} | |
fn get_roman_numerals_descending() -> Vec<RomanNumeral> { | |
vec![ | |
RomanNumeral {txt: 'M',value: 1000}, | |
RomanNumeral {txt: 'D',value: 500}, | |
RomanNumeral {txt: 'C',value: 100}, | |
RomanNumeral {txt: 'L',value: 50}, | |
RomanNumeral {txt: 'X',value: 10}, | |
RomanNumeral {txt: 'V',value: 5}, | |
RomanNumeral {txt: 'I',value: 1}, | |
] | |
} | |
fn make_roman_numeral(i: i32) -> String { | |
let descending = get_roman_numerals_descending(); | |
let mut roman_numeral = String::new(); | |
let mut remainder = i; | |
// find the largest roman numeral smaller than remainder, | |
// append the roman character, and deduct from the remainder | |
while remainder > 0 { | |
if remainder == 0 { | |
break; | |
} | |
for rn in &descending { | |
if rn.value <= remainder { | |
roman_numeral.push(rn.txt); | |
remainder -= rn.value; | |
break; | |
} | |
} | |
} | |
roman_numeral | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment