Avatar of bkhl

bkhl's solution

to Say 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.

Given a number from 0 to 999,999,999,999, spell out that number in English.

Step 1

Handle the basic case of 0 through 99.

If the input to the program is 22, then the output should be 'twenty-two'.

Your program should complain loudly if given a number outside the blessed range.

Some good test cases for this program are:

  • 0
  • 14
  • 50
  • 98
  • -1
  • 100

Extension

If you're on a Mac, shell out to Mac OS X's say program to talk out loud. If you're on Linux or Windows, eSpeakNG may be available with the command espeak.

Step 2

Implement breaking a number up into chunks of thousands.

So 1234567890 should yield a list like 1, 234, 567, and 890, while the far simpler 1000 should yield just 1 and 0.

The program must also report any values that are out of range.

Step 3

Now handle inserting the appropriate scale word between those chunks.

So 1234567890 should yield '1 billion 234 million 567 thousand 890'

The program must also report any values that are out of range. It's fine to stop at "trillion".

Step 4

Put it all together to get nothing but plain English.

12345 should give twelve thousand three hundred forty-five.

The program must also report any values that are out of range.

Extensions

Use and (correctly) when spelling out the number in English:

  • 14 becomes "fourteen".
  • 100 becomes "one hundred".
  • 120 becomes "one hundred and twenty".
  • 1002 becomes "one thousand and two".
  • 1323 becomes "one thousand three hundred and twenty-three".

Rust Specific Exercise Notes

This is slightly changed in the Rust version, compared to other language versions of this exercise. Instead of requiring you to return errors for out of range, we are using Rust's strong type system to limit input. It is much easier to make a function deal with all valid inputs, rather than requiring the user of your module to handle errors.

There is a -1 version of a test case, but it is commented out. If your function is implemented properly, the -1 test case should not compile.

Adding 'and' into number text has not been implemented in test cases.

Extension

Add capability of converting up to the max value for u64: 9,223,372,036,854,775,807.

For hints at the output this should have, look at the last test case.

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

A variation on JavaRanch CattleDrive, exercise 4a http://www.javaranch.com/say.jsp

Submitting Incomplete Solutions

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

say.rs

extern crate say;

// Note: No tests created using 'and' with numbers.
// Aparently Most American English does not use the 'and' with numbers,
// where it is common in British English to use the 'and'.

#[test]
fn test_zero() {
    assert_eq!(say::encode(0), String::from("zero"));
}

//
// If the below test is uncommented, it should not compile.
//
/*
#[test]
#[ignore]
fn test_negative() {
    assert_eq!(say::encode(-1), String::from("won't compile"));
}
*/

#[test]
#[ignore]
fn test_one() {
    assert_eq!(say::encode(1), String::from("one"));
}

#[test]
#[ignore]
fn test_fourteen() {
    assert_eq!(say::encode(14), String::from("fourteen"));
}

#[test]
#[ignore]
fn test_twenty() {
    assert_eq!(say::encode(20), String::from("twenty"));
}

#[test]
#[ignore]
fn test_twenty_two() {
    assert_eq!(say::encode(22), String::from("twenty-two"));
}

#[test]
#[ignore]
fn test_one_hundred() {
    assert_eq!(say::encode(100), String::from("one hundred"));
}

// note, using American style with no and
#[test]
#[ignore]
fn test_one_hundred_twenty() {
    assert_eq!(say::encode(120), String::from("one hundred twenty"));
}

#[test]
#[ignore]
fn test_one_hundred_twenty_three() {
    assert_eq!(say::encode(123), String::from("one hundred twenty-three"));
}

#[test]
#[ignore]
fn test_one_thousand() {
    assert_eq!(say::encode(1000), String::from("one thousand"));
}

#[test]
#[ignore]
fn test_one_thousand_two_hundred_thirty_four() {
    assert_eq!(
        say::encode(1234),
        String::from("one thousand two hundred thirty-four")
    );
}

// note, using American style with no and
#[test]
#[ignore]
fn test_eight_hundred_and_ten_thousand() {
    assert_eq!(
        say::encode(810_000),
        String::from("eight hundred ten thousand")
    );
}

#[test]
#[ignore]
fn test_one_million() {
    assert_eq!(say::encode(1_000_000), String::from("one million"));
}

// note, using American style with no and
#[test]
#[ignore]
fn test_one_million_two() {
    assert_eq!(say::encode(1_000_002), String::from("one million two"));
}

#[test]
#[ignore]
fn test_1002345() {
    assert_eq!(
        say::encode(1_002_345),
        String::from("one million two thousand three hundred forty-five")
    );
}

#[test]
#[ignore]
fn test_one_billion() {
    assert_eq!(say::encode(1_000_000_000), String::from("one billion"));
}

#[test]
#[ignore]
fn test_987654321123() {
    assert_eq!(
        say::encode(987_654_321_123),
        String::from(
            "nine hundred eighty-seven billion \
             six hundred fifty-four million \
             three hundred twenty-one thousand \
             one hundred twenty-three"
        )
    );
}

/*
  This test is only if you implemented full parsing for u64 type.
*/
#[test]
#[ignore]
fn test_max_u64() {
    assert_eq!(
        say::encode(9_223_372_036_854_775_807),
        String::from(
            "nine quintillion two hundred twenty-three \
             quadrillion three hundred seventy-two trillion \
             thirty-six billion eight hundred fifty-four million \
             seven hundred seventy-five thousand eight hundred seven"
        )
    );
}
fn word(n: u64) -> String {
    let s = match n {
        0 => "zero",
        1 => "one",
        2 => "two",
        3 => "three",
        4 => "four",
        5 => "five",
        6 => "six",
        7 => "seven",
        8 => "eight",
        9 => "nine",
        10 => "ten",
        11 => "eleven",
        12 => "twelve",
        13 => "thirteen",
        14 => "fourteen",
        15 => "fifteen",
        16 => "sixteen",
        17 => "seventeen",
        18 => "eighteen",
        19 => "nineteen",
        20 => "twenty",
        30 => "thirty",
        40 => "forty",
        50 => "fifty",
        60 => "sixty",
        70 => "seventy",
        80 => "eighty",
        90 => "ninety",
        100 => "hundred",
        1_000 => "thousand",
        1_000_000 => "million",
        1_000_000_000 => "billion",
        1_000_000_000_000 => "trillion",
        1_000_000_000_000_000 => "quadrillion",
        1_000_000_000_000_000_000 => "quintillion",
        _ => panic!(),
    };
    String::from(s)
}

pub fn encode(n: u64) -> String {
    match n {
        0 => word(0),
        _ => encode_nonzero(n),
    }
}

fn encode_nonzero(n: u64) -> String {
    let mut strings = Vec::new();

    let mut d = 1_000_000_000_000_000_000;
    let mut r = n;

    while d > 1 {
        let q = r / d;
        r = r % d;

        if q > 0 {
            strings.push(encode_hundreds(q));
            strings.push(word(d));
        }

        d /= 1000;
    }

    if r > 0 {
        strings.push(encode_hundreds(r));
    }

    strings.join(" ")
}

fn encode_hundreds(n: u64) -> String {
    let mut strings = Vec::new();

    let q = n / 100;
    let r = n % 100;

    if q > 0 {
        strings.push(word(q));
        strings.push(word(100));
    }
    if r > 0 {
        strings.push(encode_tens(r));
    }

    strings.join(" ")
}

fn encode_tens(n: u64) -> String {
    let mut strings = Vec::new();

    if n > 20 {
        let q = n / 10;
        let r = n % 10;

        if q > 0 {
            strings.push(word(q * 10));
        }

        if r > 0 {
            strings.push(word(r));
        }
    } else {
        strings.push(word(n));
    }

    strings.join("-")
}

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?