Published at Oct 07 2019
·
0 comments

Instructions

Test suite

Solution

Parse and evaluate simple math word problems returning the answer as an integer.

Problems with no operations simply evaluate to the number given.

What is 5?

Evaluates to 5.

Add two numbers together.

What is 5 plus 13?

Evaluates to 18.

Handle large numbers and negative numbers.

Now, perform the other three operations.

What is 7 minus 5?

2

What is 6 multiplied by 4?

24

What is 25 divided by 5?

5

Handle a set of operations, in sequence.

Since these are verbal word problems, evaluate the expression from
left-to-right, *ignoring the typical order of operations.*

What is 5 plus 13 plus 6?

24

What is 3 plus 2 multiplied by 3?

15 (i.e. not 9)

The parser should reject:

- Unsupported operations ("What is 52 cubed?")
- Non-math questions ("Who is the President of the United States")
- Word problems with invalid syntax ("What is 1 plus plus 2?")

If you'd like, handle exponentials.

What is 2 raised to the 5th power?

32

To get the bonus tests to run, execute the tests with:

```
$ cargo test --features exponentials
```

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.

Inspired by one of the generated questions in the Extreme Startup game. https://github.com/rchatley/extreme_startup

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

```
use wordy::answer;
#[test]
fn just_a_number() {
let command = "What is 5?";
assert_eq!(Some(5), answer(command));
}
#[test]
#[ignore]
fn addition() {
let command = "What is 1 plus 1?";
assert_eq!(Some(2), answer(command));
}
#[test]
#[ignore]
fn more_addition() {
let command = "What is 53 plus 2?";
assert_eq!(Some(55), answer(command));
}
#[test]
#[ignore]
fn addition_with_negative_numbers() {
let command = "What is -1 plus -10?";
assert_eq!(Some(-11), answer(command));
}
#[test]
#[ignore]
fn large_addition() {
let command = "What is 123 plus 45678?";
assert_eq!(Some(45_801), answer(command));
}
#[test]
#[ignore]
fn subtraction() {
let command = "What is 4 minus -12?";
assert_eq!(Some(16), answer(command));
}
#[test]
#[ignore]
fn multiplication() {
let command = "What is -3 multiplied by 25?";
assert_eq!(Some(-75), answer(command));
}
#[test]
#[ignore]
fn division() {
let command = "What is 33 divided by -3?";
assert_eq!(Some(-11), answer(command));
}
#[test]
#[ignore]
fn multiple_additions() {
let command = "What is 1 plus 1 plus 1?";
assert_eq!(Some(3), answer(command));
}
#[test]
#[ignore]
fn addition_and_subtraction() {
let command = "What is 1 plus 5 minus -2?";
assert_eq!(Some(8), answer(command));
}
#[test]
#[ignore]
fn multiple_subtraction() {
let command = "What is 20 minus 4 minus 13?";
assert_eq!(Some(3), answer(command));
}
#[test]
#[ignore]
fn subtraction_then_addition() {
let command = "What is 17 minus 6 plus 3?";
assert_eq!(Some(14), answer(command));
}
#[test]
#[ignore]
fn multiple_multiplications() {
let command = "What is 2 multiplied by -2 multiplied by 3?";
assert_eq!(Some(-12), answer(command));
}
#[test]
#[ignore]
fn addition_and_multiplication() {
let command = "What is -3 plus 7 multiplied by -2?";
assert_eq!(Some(-8), answer(command));
}
#[test]
#[ignore]
fn multiple_divisions() {
let command = "What is -12 divided by 2 divided by -3?";
assert_eq!(Some(2), answer(command));
}
#[test]
#[ignore]
fn unknown_operation() {
let command = "What is 52 cubed?";
assert_eq!(None, answer(command));
}
#[test]
#[ignore]
fn non_math_question() {
let command = "Who is the President of the United States?";
assert_eq!(None, answer(command));
}
#[test]
#[ignore]
fn reject_problem_missing_an_operand() {
let command = "What is 1 plus?";
assert_eq!(None, answer(command));
}
#[test]
#[ignore]
fn reject_problem_with_no_operands_or_operators() {
let command = "What is?";
assert_eq!(None, answer(command));
}
#[test]
#[ignore]
fn reject_two_operations_in_a_row() {
let command = "What is 1 plus plus 2?";
assert_eq!(None, answer(command));
}
#[test]
#[ignore]
fn reject_two_numbers_in_a_row() {
let command = "What is 1 plus 2 1?";
assert_eq!(None, answer(command));
}
#[test]
#[ignore]
fn reject_postfix_notation() {
let command = "What is 1 2 plus?";
assert_eq!(None, answer(command));
}
#[test]
#[ignore]
fn reject_prefix_notation() {
let command = "What is plus 1 2?";
assert_eq!(None, answer(command));
}
#[test]
#[ignore]
#[cfg(feature="exponentials")]
fn exponential() {
let command = "What is 2 raised to the 5th power?";
assert_eq!(Some(32), answer(command));
}
#[test]
#[ignore]
#[cfg(feature="exponentials")]
fn addition_and_exponential() {
let command = "What is 1 plus 2 raised to the 2nd power?";
assert_eq!(Some(9), answer(command));
}
```

```
pub struct WordProblem;
pub fn answer(command: &str) -> Option<i32> {
if !command.starts_with("What is ") {
return None;
}
parse(&command[8..]).ok()
}
enum Operation {
Add(i32),
Sub(i32),
Mul(i32),
Div(i32),
Pow(i32),
}
fn parse_operand(command: &str) -> Result<(i32, &str), ()> {
let mut command = command.trim();
let i = match command.find(|c: char| c != '-' && !c.is_digit(10)) {
Some(i) => i,
None => return Err(()),
};
let n = &command[..i].parse::<i32>().map_err(|_| ())?;
command = &command[i..].trim();
Ok((*n, command))
}
fn valid_ordinal(command: &str) -> bool {
command.starts_with("st")
|| command.starts_with("nd")
|| command.starts_with("rd")
|| command.starts_with("th")
}
const ORDINAL_LEN: usize = 2;
fn parse_operation(command: &str) -> Result<(Operation, &str), ()> {
let command = command.trim();
if command.starts_with("plus") {
let (n, remainder) = parse_operand(&command[4..].trim())?;
return Ok((Operation::Add(n), remainder));
}
if command.starts_with("minus") {
let (n, remainder) = parse_operand(&command[5..].trim())?;
return Ok((Operation::Sub(n), remainder));
}
if command.starts_with("multiplied by") {
let (n, remainder) = parse_operand(&command[13..].trim())?;
return Ok((Operation::Mul(n), remainder));
}
if command.starts_with("divided by") {
let (n, remainder) = parse_operand(&command[10..].trim())?;
return Ok((Operation::Div(n), remainder));
}
if command.starts_with("raised to the") {
let (n, remainder) = parse_operand(&command[13..].trim())?;
if !valid_ordinal(remainder) {
return Err(());
}
let remainder = &remainder[ORDINAL_LEN..].trim();
if !remainder.starts_with("power") {
return Err(());
}
return Ok((Operation::Pow(n), &remainder[5..]));
}
Err(())
}
fn parse(command: &str) -> Result<i32, ()> {
let (mut total, mut command) = parse_operand(&command)?;
command = command.trim();
while !command.starts_with("?") {
let (op, remainder) = parse_operation(&command)?;
match op {
Operation::Add(n) => total += n,
Operation::Sub(n) => total -= n,
Operation::Mul(n) => total *= n,
Operation::Div(n) => total /= n,
Operation::Pow(n) => total = total.pow(n as u32),
}
command = remainder.trim();
}
Ok(total)
}
```

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,091 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments