Avatar of bkhl

bkhl's solution

to Roman Numerals in the Rust Track

Published at Jan 05 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Write a function to convert from normal numbers to Roman Numerals.

The Romans were a clever bunch. They conquered most of Europe and ruled it for hundreds of years. They invented concrete and straight roads and even bikinis. One thing they never discovered though was the number zero. This made writing and dating extensive histories of their exploits slightly more challenging, but the system of numbers they came up with is still in use today. For example the BBC uses Roman numerals to date their programmes.

The Romans wrote numbers using letters - I, V, X, L, C, D, M. (notice these letters have lots of straight lines and are hence easy to hack into stone tablets).

 1  => I
10  => X
 7  => VII

There is no need to be able to convert numbers larger than about 3000. (The Romans themselves didn't tend to go any higher)

Wikipedia says: Modern Roman numerals ... are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero.

To see this in practice, consider the example of 1990.

In Roman numerals 1990 is MCMXC:

1000=M 900=CM 90=XC

2008 is written as MMVIII:

2000=MM 8=VIII

See also: http://www.novaroma.org/via_romana/numbers.html

Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

Writing the Code

Execute the tests with:

$ cargo test

All but the first test have been ignored. After you get the first test to pass, open the tests source file wich is located in the tests directory and remove the #[ignore] flag from the next test and get the tests to pass again. Each separate test is a function with #[test] flag above it. Continue, until you pass every test.

If you wish to run all tests without editing the tests source file, use:

$ cargo test -- --ignored

To run a specific test, for example some_test, you can use:

$ cargo test some_test

If the specfic test is ignored use:

$ cargo test some_test -- --ignored

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

Feedback, Issues, Pull Requests

The exercism/rust repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the contribution guide.

Source

The Roman Numeral Kata http://codingdojo.org/cgi-bin/index.pl?KataRomanNumerals

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

roman-numerals.rs

extern crate roman_numerals;

use roman_numerals::*;

#[test]
fn test_one() {
    assert_eq!("I", Roman::from(1).to_string());
}

#[test]
#[ignore]
fn test_two() {
    assert_eq!("II", Roman::from(2).to_string());
}

#[test]
#[ignore]
fn test_three() {
    assert_eq!("III", Roman::from(3).to_string());
}

#[test]
#[ignore]
fn test_four() {
    assert_eq!("IV", Roman::from(4).to_string());
}

#[test]
#[ignore]
fn test_five() {
    assert_eq!("V", Roman::from(5).to_string());
}

#[test]
#[ignore]
fn test_six() {
    assert_eq!("VI", Roman::from(6).to_string());
}

#[test]
#[ignore]
fn test_nine() {
    assert_eq!("IX", Roman::from(9).to_string());
}

#[test]
#[ignore]
fn test_twenty_seven() {
    assert_eq!("XXVII", Roman::from(27).to_string());
}

#[test]
#[ignore]
fn test_forty_eight() {
    assert_eq!("XLVIII", Roman::from(48).to_string());
}

#[test]
#[ignore]
fn test_fifty_nine() {
    assert_eq!("LIX", Roman::from(59).to_string());
}

#[test]
#[ignore]
fn test_ninety_three() {
    assert_eq!("XCIII", Roman::from(93).to_string());
}

#[test]
#[ignore]
fn test_141() {
    assert_eq!("CXLI", Roman::from(141).to_string());
}

#[test]
#[ignore]
fn test_163() {
    assert_eq!("CLXIII", Roman::from(163).to_string());
}

#[test]
#[ignore]
fn test_402() {
    assert_eq!("CDII", Roman::from(402).to_string());
}

#[test]
#[ignore]
fn test_575() {
    assert_eq!("DLXXV", Roman::from(575).to_string());
}

#[test]
#[ignore]
fn test_911() {
    assert_eq!("CMXI", Roman::from(911).to_string());
}

#[test]
#[ignore]
fn test_1024() {
    assert_eq!("MXXIV", Roman::from(1024).to_string());
}

#[test]
#[ignore]
fn test_3000() {
    assert_eq!("MMM", Roman::from(3000).to_string());
}
use std::fmt;

extern crate num;
use num::{Integer, ToPrimitive, Unsigned};

#[derive(Clone, Copy)]
enum RomanDigit {
    I = 1,
    V = 5,
    X = 10,
    L = 50,
    C = 100,
    D = 500,
    M = 1000,
}

pub struct Roman(Vec<RomanDigit>);

impl<T> From<T> for Roman
where
    T: Integer + Unsigned + ToPrimitive,
{
    fn from(n: T) -> Self {
        let mut v = Vec::<RomanDigit>::new();
        let i = n.to_usize().unwrap();

        let i = from_partial(RomanDigit::M, RomanDigit::D, RomanDigit::C, &mut v, i);
        let i = from_partial(RomanDigit::C, RomanDigit::L, RomanDigit::X, &mut v, i);
        from_partial(RomanDigit::X, RomanDigit::V, RomanDigit::I, &mut v, i);

        Roman(v)
    }
}

fn from_partial(
    high: RomanDigit,
    mid: RomanDigit,
    low: RomanDigit,
    numeral: &mut Vec<RomanDigit>,
    mut remainder: usize,
) -> usize {
    while remainder >= high as usize {
        numeral.push(high);
        remainder -= high as usize;
    }

    if remainder >= high as usize - low as usize {
        numeral.push(low);
        numeral.push(high);
        remainder -= high as usize - low as usize;
    }

    if remainder >= mid as usize {
        numeral.push(mid);
        remainder -= mid as usize;
    }

    if remainder >= mid as usize - low as usize {
        numeral.push(low);
        numeral.push(mid);
        remainder -= mid as usize - low as usize;
    }

    while remainder >= low as usize {
        numeral.push(low);
        remainder -= low as usize;
    }

    remainder
}

impl fmt::Display for Roman {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let Roman(digits) = self;

        digits
            .iter()
            .map(|digit| match digit {
                RomanDigit::I => 'I',
                RomanDigit::V => 'V',
                RomanDigit::X => 'X',
                RomanDigit::L => 'L',
                RomanDigit::C => 'C',
                RomanDigit::D => 'D',
                RomanDigit::M => 'M',
            })
            .collect::<String>()
            .fmt(f)
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?