ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Apr 04 2021
·
0 comments

Instructions

Test suite

Solution

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

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

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`

.

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.

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".

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.

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".

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.

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.

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

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 which 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 ignored 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 specific 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.

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

```
cargo fmt
```

To see, if your solution contains some common ineffective use cases, inside the solution directory use

```
cargo clippy --all-targets
```

Generally you should submit all files in which you implemented your solution (`src/lib.rs`

in most cases). If you are using any external crates, please consider submitting the `Cargo.toml`

file. This will make the review process faster and clearer.

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.

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

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

```
// Note: No tests created using 'and' with numbers.
// Apparently 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"
)
);
}
/*
These tests are only if you implemented full parsing for u64 type.
*/
#[test]
#[ignore]
fn test_max_i64() {
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"
)
);
}
#[test]
#[ignore]
fn test_max_u64() {
assert_eq!(
say::encode(18_446_744_073_709_551_615),
String::from(
"eighteen quintillion four hundred forty-six \
quadrillion seven hundred forty-four trillion \
seventy-three billion seven hundred nine million \
five hundred fifty-one thousand six hundred fifteen"
)
);
}
```

```
use itertools::Itertools;
const SCALE_WORDS: [&str; 7] = [
"",
"thousand",
"million",
"billion",
"trillion",
"quadrillion",
"quintillion",
];
pub fn encode(n: u64) -> String {
let thousand_splits = split_number_to_thousands(&n);
// Assign scale word index to thousand splits
let scale_indexed: Vec<(usize, u16)> = thousand_splits
.iter()
// Reverse so enumerate index can be assigned starting from least significant split group
.rev()
.enumerate()
.map(|(index, value)| (index, *value))
// Restore original order
.rev()
.collect();
scale_indexed
.iter()
.filter_map(|(index, value)| {
// Remove thousand groups which containing zero and have a group in front.
match (value, scale_indexed.get(index + 1)) {
(0, Some(_)) => None,
_ => Some((index, value)),
}
})
.map(|(scale_index, value)| {
[&number_to_text(value), " ", SCALE_WORDS[*scale_index]]
.concat()
// Get rid of ending whitespace if scale word is empty
.trim_end()
.to_string()
})
.join(" ")
}
pub fn split_number_to_thousands(number: &u64) -> Vec<u16> {
const GROUPING: u64 = 1000;
let mut remainder = *number;
let mut split = Vec::new();
while remainder >= GROUPING {
let part = (remainder % GROUPING) as u16;
split.insert(0, part);
remainder /= GROUPING;
}
let last_group = remainder as u16;
split.insert(0, last_group);
split
}
fn number_to_text(number: &u16) -> String {
let digits = number_to_digits(number);
match digits.as_slice() {
[hundreds, 0, 0] => match_hundreds(hundreds),
[hundreds, 0, ones] => [&match_hundreds(hundreds), " ", match_ones(ones)].concat(),
[hundreds, tens, 0] => [&match_hundreds(hundreds), " ", match_tens(tens)].concat(),
[hundreds, tens, ones] => [
&match_hundreds(hundreds),
" ",
&match_tens_and_ones(tens, ones),
]
.concat(),
[tens, 0] => match_tens(tens).to_string(),
[tens, ones] => match_tens_and_ones(tens, ones),
[ones] => match_ones(ones).to_string(),
_ => "".to_string(),
}
}
pub fn number_to_digits(number: &u16) -> Vec<u8> {
const DIGIT_BASE: u16 = 10;
let mut digits = Vec::new();
let mut remainder = *number;
while remainder > 9 {
let digit = (remainder % DIGIT_BASE) as u8;
digits.insert(0, digit);
remainder /= DIGIT_BASE;
}
let last_digit = remainder as u8;
digits.insert(0, last_digit);
digits
}
fn match_hundreds(digit: &u8) -> String {
[match_ones(digit), " hundred"].concat()
}
fn match_tens_and_ones(tens: &u8, ones: &u8) -> String {
const TENS_DIGIT_TEN: u8 = 1;
match (tens, ones) {
(0, ones) => match_ones(ones).to_string(),
(tens, 0) => match_tens(tens).to_string(),
(tens, ones) if *tens == TENS_DIGIT_TEN => match_teens(&(tens * 10 + ones)).to_string(),
_ => [match_tens(tens), "-", match_ones(ones)].concat(),
}
}
fn match_ones<'a>(digit: &u8) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => panic!("{} not match with 0-9 range", digit),
}
}
fn match_tens<'a>(digit: &u8) -> &'a str {
match digit {
1 => "ten",
2 => "twenty",
3 => "thirty",
4 => "forty",
5 => "fifty",
6 => "sixty",
7 => "seventy",
8 => "eighty",
9 => "ninety",
_ => panic!("{} not match with tens", digit),
}
}
fn match_teens<'a>(digit: &u8) -> &'a str {
match digit {
11 => "eleven",
12 => "twelve",
13 => "thirteen",
14 => "fourteen",
15 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen",
_ => panic!("{} not match with 11-19 range", digit),
}
}
```

```
[package]
edition = "2018"
name = "say"
version = "1.2.0"
[dependencies]
itertools = "0.10.0"
```

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?

Level up your programming skills with 3,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments