Browse Source

rpn-calculator

master
Akshay Dixit 4 years ago
parent
commit
ea5982d962
  1. 4
      rust/rpn-calculator/Cargo.toml
  2. 85
      rust/rpn-calculator/HELP.md
  3. 5
      rust/rpn-calculator/HINTS.md
  4. 147
      rust/rpn-calculator/README.md
  5. 39
      rust/rpn-calculator/src/lib.rs
  6. 86
      rust/rpn-calculator/tests/rpn-calculator.rs

4
rust/rpn-calculator/Cargo.toml

@ -0,0 +1,4 @@
[package]
name = "rpn_calculator"
version = "0.1.0"
edition = "2021"

85
rust/rpn-calculator/HELP.md

@ -0,0 +1,85 @@
# Help
## Running the tests
Execute the tests with:
```bash
$ 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 _only ignored_ tests without editing the tests source file, use:
```bash
$ cargo test -- --ignored
```
If you are using Rust 1.51 or later, you can run _all_ tests with
```bash
$ cargo test -- --include-ignored
```
To run a specific test, for example `some_test`, you can use:
```bash
$ cargo test some_test
```
If the specific test is ignored, use:
```bash
$ cargo test some_test -- --ignored
```
To learn more about Rust tests refer to the online [test documentation][rust-tests].
[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html
## Submitting your solution
You can submit your solution using the `exercism submit src/lib.rs Cargo.toml` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Rust track's documentation](https://exercism.org/docs/tracks/rust)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
## Rust Installation
Refer to the [exercism help page][help-page] for Rust installation and learning
resources.
## Submitting the solution
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.
## Feedback, Issues, Pull Requests
The GitHub [track repository][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].
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
[help-page]: https://exercism.org/tracks/rust/learning
[github]: https://github.com/exercism/rust
[contribution guide]: https://exercism.org/docs/community/contributors

5
rust/rpn-calculator/HINTS.md

@ -0,0 +1,5 @@
# Hints
## General
- Look at the documentation for `std::vec::Vec`'s [`push()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.push) and ['pop()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.pop) methods.

147
rust/rpn-calculator/README.md

@ -0,0 +1,147 @@
# RPN Calculator
Welcome to RPN Calculator on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
[Stacks](https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29) are a type of collection commonly used in computer science.
They are defined by their two key operations: **push** and **pop**.
**Push** adds an element to the top of the stack.
**Pop** removes and returns the topmost element.
Think of a stack like a stack of plates.
You can either add a plate to the top of the stack or take the topmost plate.
To access something further down, you have to remove all of the plates above it.
Rust's vector implementation, [`std::vec::Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html), can be used as a stack by using its `push()` and `pop()` methods.
Naturally, `push()` adds an element to the end of the `Vec` and `pop()` removes and returns the last element.
These operation can be very fast (O(1) in [Big O Notation](https://en.wikipedia.org/wiki/Big_O_notation)),
so they are one of the most idiomatic ways to use a `Vec`.
Stacks are useful to hold arbitrary numbers of elements in a specific order.
Because the last element inserted is the first element returned,
stacks are commonly refered to as **LIFO** (Last-In, First-Out).
This inherent ordering can be used for many things,
including tracking state when evaulating **Reverse Polish notation**.
## Instructions
## 1. Overview
[Reverse Polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation) (RPN) is a way of writing mathematical expressions.
Unlike in traditional infix notation, RPN operators *follow* their operands.
For example, instead of writing:
```
2 + 2
```
you would write:
```
2 2 +
```
The major benefit of Reverse Polish notation is that it is much simpler to parse than infix notation.
RPN eliminates the need for order of operations or parentheses in complex expressions.
For example:
```
(4 + 8) / (7 - 5)
```
can be written as
```
4 8 + 7 5 - /
```
In both cases, the expression evaluates to 6.
## 2. Example
Let's manually evaluate that complex expression.
As we learned in the introduction, evaluation of RPN requires a stack.
This stack is used to hold numeric values that the operators operate on.
We start our calculator with an empty stack and then evaluate each element one at a time.
First, we encounter a `4`,
so we push it onto our freshly created stack.
```
4
```
Next, we encounter an `8`.
We also push that onto the stack.
```
4 8
```
Now, we encounter a `+`.
We pop off the two topmost values (4 and 8),
add them together,
and push the sum back onto the stack.
```
12
```
We do something similar for `7`, `5`, and `-`:
```
12 7
12 7 5
12 2
```
Now we encounter a `/`.
Even though we last encountered a `-`,
there are two elements on the stack.
We pop off the two elements,
divide them,
and push the result back onto the stack.
```
6
```
Finally, since there is exactly one element on the stack,
we can say the expression evaluated to 6.
## 3. Goal
Your goal is to write a calculator to evaluate a list of inputs ordered by Reverse Polish notation and return the final element on the stack.
If there is not exactly one element in the stack at the end, return `None`.
If there is an operator with too few operands (such as the input `2 +`), return `None`.
You are given the following enum and stubbed function as a starting point.
```rust
#[derive(Debug)]
pub enum CalculatorInput {
Add,
Subtract,
Multiply,
Divide,
Value(i32),
}
pub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {
unimplemented!(
"Given the inputs: {:?}, evaluate them as though they were a Reverse Polish notation expression",
inputs,
);
}
```
## Source
### Created by
- @cwhakes

39
rust/rpn-calculator/src/lib.rs

@ -0,0 +1,39 @@
#[derive(Debug)]
pub enum CalculatorInput {
Add,
Subtract,
Multiply,
Divide,
Value(i32),
}
pub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {
let mut stack = Vec::<i32>::new();
for input in inputs {
if let CalculatorInput::Value(v) = input {
stack.push(*v);
} else {
let result = try_eval(&mut stack, input)?;
stack.push(result);
}
}
if stack.len() == 1 {
Some(stack.pop().unwrap())
} else {
None
}
}
fn try_eval(stack: &mut Vec<i32>, op: &CalculatorInput) -> Option<i32> {
let b = stack.pop()?;
let a = stack.pop()?;
match op {
CalculatorInput::Add => Some(a + b),
CalculatorInput::Subtract => Some(a-b),
CalculatorInput::Divide => Some(a/b),
CalculatorInput::Multiply => Some(a*b),
_ => None
}
}

86
rust/rpn-calculator/tests/rpn-calculator.rs

@ -0,0 +1,86 @@
use rpn_calculator::*;
fn calculator_input(s: &str) -> Vec<CalculatorInput> {
s.split_whitespace()
.map(|s| match s {
"+" => CalculatorInput::Add,
"-" => CalculatorInput::Subtract,
"*" => CalculatorInput::Multiply,
"/" => CalculatorInput::Divide,
n => CalculatorInput::Value(n.parse().unwrap()),
})
.collect()
}
#[test]
fn test_empty_input_returns_none() {
let input = calculator_input("");
assert_eq!(evaluate(&input), None);
}
#[test]
fn test_simple_value() {
let input = calculator_input("10");
assert_eq!(evaluate(&input), Some(10));
}
#[test]
fn test_simple_addition() {
let input = calculator_input("2 2 +");
assert_eq!(evaluate(&input), Some(4));
}
#[test]
fn test_simple_subtraction() {
let input = calculator_input("7 11 -");
assert_eq!(evaluate(&input), Some(-4));
}
#[test]
#[ignore]
fn test_simple_multiplication() {
let input = calculator_input("6 9 *");
assert_eq!(evaluate(&input), Some(54));
}
#[test]
#[ignore]
fn test_simple_division() {
let input = calculator_input("57 19 /");
assert_eq!(evaluate(&input), Some(3));
}
#[test]
#[ignore]
fn test_complex_operation() {
let input = calculator_input("4 8 + 7 5 - /");
assert_eq!(evaluate(&input), Some(6));
}
#[test]
#[ignore]
fn test_too_few_operands_returns_none() {
let input = calculator_input("2 +");
assert_eq!(evaluate(&input), None);
}
#[test]
#[ignore]
fn test_too_many_operands_returns_none() {
let input = calculator_input("2 2");
assert_eq!(evaluate(&input), None);
}
#[test]
#[ignore]
fn test_zero_operands_returns_none() {
let input = calculator_input("+");
assert_eq!(evaluate(&input), None);
}
#[test]
#[ignore]
fn test_intermediate_error_returns_none() {
let input = calculator_input("+ 2 2 *");
assert_eq!(evaluate(&input), None);
}
Loading…
Cancel
Save