Skip to content

Instantly share code, notes, and snippets.

@BrianKopp
Last active June 13, 2020 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrianKopp/a96f1273b030c408e2708eff93cbc288 to your computer and use it in GitHub Desktop.
Save BrianKopp/a96f1273b030c408e2708eff93cbc288 to your computer and use it in GitHub Desktop.
Programming Challenge - Rust - Roman Numerals Checkpoint 3
fn make_roman_numeral(my_int: i32) -> String {
let descending = get_roman_numerals_descending();
let mut roman_numeral = String::new();
let mut remainder = my_int;
// find the largest roman numeral smaller than remainder,
// append the roman character, and deduct from the remainder,
// if roman numeral is not smaller, try the next valid subtractor.
// e.g. if remainder is smaller than 10, X, then check if remainder
// is smaller than 9, IX, else go down to next numeral, V.
while remainder > 0 {
if remainder == 0 {
break;
}
for (i, rn) in descending.iter().enumerate() {
if rn.value <= remainder {
roman_numeral.push_str(&rn.txt);
remainder -= rn.value;
break;
}
let next_valid_subtractor = subtractor_value(&descending, i);
if next_valid_subtractor.is_some() {
let next_sub = next_valid_subtractor.unwrap();
if next_sub.value <= remainder {
roman_numeral.push_str(&next_sub.txt);
remainder -= next_sub.value;
break;
}
}
}
}
roman_numeral
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment