Browse Source

Merge pull request #765 from 01-edu/exam-rust-review-new-exercises

Exam rust review new exercises
content-update
augusto-mantilla 3 years ago committed by GitHub
parent
commit
77b9148c4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 17
      subjects/display_table/README.md
  2. 26
      subjects/filter_table/README.md
  3. 5
      subjects/flat_tree/README.md
  4. BIN
      subjects/insertion_sort/Insertion-Sort-demo.jpg
  5. BIN
      subjects/insertion_sort/Insertion-Sort-demo.png
  6. 42
      subjects/insertion_sort/README.md
  7. 45
      subjects/lunch_queue/README.md
  8. 10
      subjects/matrix_display/README.md
  9. 33
      subjects/matrix_transposition_4by3/README.md
  10. 2
      subjects/nextprime/README.md
  11. 19
      subjects/order_books/README.md
  12. 4
      subjects/previousprime/README.md
  13. 32
      subjects/queens/README.md
  14. 11
      subjects/reverse_it/README.md
  15. 12
      subjects/rot21/README.md
  16. 27
      subjects/rpn/README.md

17
subjects/display_table/README.md

@ -2,37 +2,42 @@
### Instructions
- Implement the std::fmt::Display trait for the structure table so the table is printed like in the [Usage](#usage) the length of each column must adjust to the longest element of the column and the element must be centered in the "cell" when possible, if the length of the element doesn't allow to center exactly it must alight slightly to the right.
- Implement the `std::fmt::Display` trait for the structure table so that the table is printed like in the **[Usage](#usage)**. The length of each column must adjust to the longest element of the column and the element must be centered in the "cell" when possible. If the length of the element doees not allow to center exactly, it must descend slightly to the right.
- Note: If the table is empty `println!` must not print anything.
- Define the associated function `new` that create a new empty table.
- Define the associated function `new` which creates a new empty table.
- Define the method function `add_row` that adds a new row to the table created from a slice of strings.
- Define the method function `add_row` which adds a new row to the table created from a slice of strings.
### Expected function
### Expected functions and Structures
```rust
#[derive(Clone, Debug, PartialEq)]
pub struct Table {
pub headers: Vec<String>,
pub body: Vec<Vec<String>>,
}
impl fmt::Display for Table {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
}
impl Table {
pub fn new() -> Table {
}
}
pub fn add_row(&mut self, row: &[String]) {
}
}
```
### Usage
Here is a possible test for your function:
Here is a possible program to test your function:
```rust
fn main() {

26
subjects/filter_table/README.md

@ -2,23 +2,24 @@
### Instructions
- Define the functions:
- Define the **functions**:
- new: creates a new empty table.
- new: which creates a new empty table.
- add_rows: adds a new row to the table from a slice of strings.
- filter_cols: that receives a closure that receives a `&str` and returns a `bool` value:
- add_rows: which adds a new row to the table from a slice of strings.
- filter_cols returns a table with all the columns that yielded true when applied to the header.
- filter_rows: that receives a closure that receives a `&str` and returns a `bool` value
- filter_cols: which receives a closure which receives a `&str` and returns a `bool` value:
- filter_rows returns a table with all the columns that yielded true when applied to the elements of the selected column.
- filter_cols returns a table with all the columns that yielded true when applied to the header.
### Expected function
- filter_rows: which receives a closure that receives a `&str` and returns a `bool` value
- filter_rows returns a table with all the columns that yielded true when applied to the elements of the selected column.
### Expected functions and Structures
```rust
#[derive(Clone, Debug, PartialEq)]
pub struct Table {
pub headers: Vec<String>,
pub body: Vec<Vec<String>>,
@ -26,9 +27,11 @@ pub struct Table {
impl Table {
pub fn new() -> Table {
}
pub fn add_row(&mut self, row: &[String]) {
}
pub fn filter_col(&self, filter: ) -> Option<Self> {
@ -36,13 +39,14 @@ impl Table {
}
pub fn filter_row(&self, col_name: &str, filter: ) -> Option<Self> {
}
}
```
### Usage
Here is a possible test for your function:
Here is a possible program to test your function:
```rust
fn main() {

5
subjects/flat_tree/README.md

@ -2,18 +2,19 @@
### Instructions
- Define the functions `flatten_tree` that receives a std::collections::BTreeSet and returns a new `Vec` with the elements in the binary tree in order.
- Define the functions `flatten_tree` which receives a `std::collections::BTreeSet` and returns a new `Vec` with the elements of the binary tree in order.
### Expected function
```rust
pub fn flatten_tree<T: ToOwned<Owned = T>>(tree: &BTreeSet<T>) -> Vec<T> {
}
```
### Usage
Here is a possible test for your function:
Here is a possible program to test your function:
```rust
fn main() {

BIN
subjects/insertion_sort/Insertion-Sort-demo.jpg

diff.bin_not_shown

Before

Width:  |  Height:  |  Size: 66 KiB

BIN
subjects/insertion_sort/Insertion-Sort-demo.png

diff.bin_not_shown

After

Width:  |  Height:  |  Size: 119 KiB

42
subjects/insertion_sort/README.md

@ -2,51 +2,51 @@
### Instructions
The insertion sort algorithm:
- Implement the insertion sort algorithm by creating a function `insertion_sort(slice, steps)` which executes the iterations of the algorithm **up to** the number of steps indicated by the parameter `steps`. See the **Usage** for more information.
- To sort an array of size n in ascending order:
The insertion sort algorithm to sort an array of size n in ascending order:
1. Iterate from slice[1] to slice[n] over the slice.
1. Iterates from slice[1] to slice[n] over the slice.
2. Compare the current element (key) to its predecessor.
2. Compares the current element (key) to its predecessor.
3. If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.
3. If the key element is smaller than its predecessor, compares it to the elements before. Move the greater elements one position up to make space for the swapped element.
Here is a visual example of sorting a slice step by step using the insertion sort algorithm.
![](Insertion-Sort-demo.jpg)
**Figure 1** - Step by step execution of the algorithm insertion sort
![image.png](Insertion-Sort-demo.png)
- Implement the algorithm insertion sort by creating a function `insertion_sort(slice, steps)` that executes the iterations of the algorithm the number of steps indicated by the parameter `steps`. See the [Usage](#usage) for more information.
**Figure 1** - Step by step execution of the algorithm insertion sort
### Expected Function
```rust
pub fn insertion_sort(slice: &mut [i32], steps: usize) {
}
```
### Usage
Here is a possible program to test your function
Here is a possible program to test your function,
```rust
fn main() {
let mut target = [5, 3, 7, 2, 1, 6, 8, 4];
// executes the first iteration of the algorithm
insertion_sort(&mut target, 1);
println!("{:?}", target);
let mut target = [5, 3, 7, 2, 1, 6, 8, 4];
let len = target.len();
// executes len - 1 iterations of the algorithm
// i.e. sorts the slice
insertion_sort(&mut target, len - 1);
println!("{:?}", target);
let mut target = [5, 3, 7, 2, 1, 6, 8, 4];
// executes the first iteration of the algorithm
insertion_sort(&mut target, 1);
println!("{:?}", target);
let mut target = [5, 3, 7, 2, 1, 6, 8, 4];
let len = target.len();
// executes len - 1 iterations of the algorithm
// i.e. sorts the slice
insertion_sort(&mut target, len - 1);
println!("{:?}", target);
}
```
And it's output:
And its output:
```console
student@ubuntu:~/[[ROOT]]/test$ cargo run

45
subjects/lunch_queue/README.md

@ -2,23 +2,27 @@
### Instructions
You will have to create an API to organize a queue of people.
An API will have to be created to organize a queue of people.
Using the given code create the following functions:
Using the given code declare the following functions:
- `new` that will initialize the `Queue`.
- `add` that receives the person's information, so it can be added to the `Queue`
- `invert_queue` that invert the queue of persons
- `rm`, that will remove the person that finished ordering their food.
The method for organizing the manipulation of a data structure should be a
FIFO (first in first out) process. This function should return a tuple wrapped in an `Option`
with the information of that person
- `search`, that return a tuple with the information of a given person `id`.
- `new` which will initialize the `Queue`
- `add` which receives the person's information, so it can be added to the `Queue`
- `invert_queue` which inverts the queue of persons
- `rm`, which will remove the person who finished ordering their food.
The removal should respect a FIFO system (first in first out). This function should return a tuple wrapped in an `Option` with the information of the removed person (check the usage)
- `search`, which returns a tuple with the information of a given person `id`
You must also create a type called `Link` this will be the connection of the structures `Queue` and `Person`.
You must also create a type called `Link`. This will be the connection of the structures `Queue` and `Person`.
Do not forget that this will be a recursion type and it must point to `None` if there is no persons.
### Expected Function
### Notions
- [enum](https://doc.rust-lang.org/rust-by-example/custom_types/enum.html)
- [Box](https://doc.rust-lang.org/book/ch15-01-box.html)
- [std::option](https://doc.rust-lang.org/std/option/)
### Expected Function adn Structures
```rust
pub struct Queue {
@ -44,7 +48,7 @@ impl Queue {
### Usage
Here is a program to test your function
Here is a program to test your function:
```rust
fn main() {
@ -61,7 +65,8 @@ fn main() {
println!("removed {:?}", list.rm());
println!("list {:?}", list);
println!("invert {:?}", list.invert_queue());
list.invert_queue();
println!("invert {:?}", list);
}
```
@ -74,15 +79,7 @@ Some(("Marie", 20))
Some(("Alice", 35))
None
removed Some(("Marie", 20))
removed Some(("Monica", 15))
list Queue { node: Some(Person { name: "Alice", discount: 35, next_person: Some(Person { name: "Ana", discount: 5, next_person: None }) }) }
inverted list Queue { node: Some(Person { name: "Ana", discount: 5, next_person: Some(Person { name: "Alice", discount: 35, next_person: None }) }) }
list Queue { node: Some(Person { name: "Alice", discount: 35, next_person: Some(Person { name: "Ana", discount: 5, next_person: Some(Person { name: "Monica", discount: 15, next_person: None }) }) }) }
invert Queue { node: Some(Person { name: "Monica", discount: 15, next_person: Some(Person { name: "Ana", discount: 5, next_person: Some(Person { name: "Alice", discount: 35, next_person: None }) }) }) }
student@ubuntu:~/[[ROOT]]/test$
```
### Notions
- https://doc.rust-lang.org/rust-by-example/custom_types/enum.html
- https://doc.rust-lang.org/book/ch15-01-box.html
- https://doc.rust-lang.org/std/option/
- https://doc.rust-lang.org/book/ch15-01-box.html

10
subjects/matrix_display/README.md

@ -4,19 +4,23 @@
Use the Matrix struct given in the [expected struct](#expected-functions-and-struct) and implement the `std::fmt::Display` trait so it prints the matrix like in the [usage](#usage).
You will also have to implement the associated function `new` that creates a matrix from a slice of slices.
The associated function `new` that creates a matrix from a slice of slices also has to be implemented.
### Expected Functions and Struct
```rust
pub struct Matrix(pub Vec<Vec<i32>>);
pub fn new(slice: &[&[i32]]) -> Self {
impl Matrix {
pub fn new(slice: &[&[i32]]) -> Self {
}
}
use std::fmt;
impl fmt::Display for Matrix {
}
```
@ -25,8 +29,6 @@ impl fmt::Display for Matrix {
Here is a possible program to test your function
```rust
use matrix_display::*;
fn main() {
let matrix = Matrix::new(&[&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]]);
println!("{}", matrix);

33
subjects/matrix_transposition_4by3/README.md

@ -4,62 +4,63 @@
- Define the structure matrix as a tuple of tuples of `i32`'s
- Define a function that calculate the transpose matrix of a 4x3 matrix (4 rows by 3 columns) which is a 3x4 matrix (3 rows by 4 columns).
- Define a **function** which calculates the transpose matrix of a 4x3 matrix (4 rows by 3 columns) which is a 3x4 matrix (3 rows by 4 columns).
- Note:
- The transpose of a matrix `A` is the matrix `A'` where `A'`'s columns are `A`'s row and the rows are the columns:
- The transpose of a matrix `A` is the matrix `A'` where `A'`'s columns are `A`'s row and the rows are the columns:
Example:
```
```console
( a b c ) __ transposition __> ( a d g j )
( d e f ) ( b e h k )
( g h i ) ( c f i l )
( j k l )
```
- Matrix must implement Debug, PartialEq and Eq. You can use derive
- Matrix must implement Debug, PartialEq and Eq. You can use derive.
- Remember that you're defining a library so you have to make public the elements that are going to be called from an external crate.
- Remember that a library has to be defined so the elements mube made public in order to be called from an external crate.
### Notions
[Chapter 7]( https://doc.rust-lang.org/stable/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html )
[paths for referring to an item in the module tree](https://doc.rust-lang.org/stable/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html)
### Expected Function and Structs
```rust
pub struct Matrix4by3(
pub (i32, i32, i32),
pub (i32, i32, i32),
pub (i32, i32, i32),
pub (i32, i32, i32),
pub (i32, i32, i32),
pub (i32, i32, i32),
pub (i32, i32, i32),
pub (i32, i32, i32),
);
pub struct Matrix3by4(
pub (i32, i32, i32, i32),
pub (i32, i32, i32, i32),
pub (i32, i32, i32, i32),
pub (i32, i32, i32, i32),
pub (i32, i32, i32, i32),
pub (i32, i32, i32, i32),
);
pub fn transpose(m: Matrix4by3) -> Matrix3by4 {
}
```
### Usage
Here is a posible program to test your function
Here is a possible program to test your function,
```rust
fn main() {
let matrix = Matrix4by3((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12));
let matrix = Matrix4by3((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12));
println!("Original matrix {:?}", matrix);
println!("Transpose matrix {:?}", transpose(matrix));
}
```
And it's output:
And its output:
```console
student@ubuntu:~/[[ROOT]]/test$ cargo run

2
subjects/nextprime/README.md

@ -2,7 +2,7 @@
### Instructions
Write a function that returns the first prime number that is equal or superior to the `int` passed as parameter.
Write a **function** which returns the first prime number which is equal or superior to the `u64` passed as parameter.
The function must be optimized in order to avoid time-outs with the tester.

19
subjects/order_books/README.md

@ -2,29 +2,31 @@
### Instructions
Build a module called `library` with two sub-modules inside it:
Build a module called `library` with two sub-modules inside of it:
- `writers` which contains a structure called `Writer` that has a first_name (String), last_name (String) and a set of books (Vec\<Book\>).
- `books` which contains a structure called `Book` that has a title (String) and a year of publish (u64).
- `writers` which contains a structure called `Writer` which has a first_name (String),a last_name (String) and a set of books (Vec\<Book\>).
- `books` which contains a structure called `Book` which has a title (String) and a year of publication (u64).
You will also have to create (outside the previous modules) a function `order_books` that receives a writer (Writer) and orders the set of books alphabetically.
A function `order_books` also has to be created (outside the previous modules which receives a writer (Writer) and orders the set of books alphabetically.
### Expected Functions and Structs
#### (The structs declarations need to be filled and added in the appropriate submodules)
```rs
pub fn order_books(writer: &mut Writer) {
pub struct Writer {
}
```
```rs
struct Writer {
pub struct Book {
}
```
```rs
struct Book {
pub fn order_books(writer: &mut Writer) {
}
```
@ -34,6 +36,9 @@ struct Book {
Here is a program to test your function and structs:
```rs
pub use library::writers::Writer;
pub use library::books::Book;
fn main() {
let mut writer_a = Writer {
first_name: "William".to_string(),

4
subjects/previousprime/README.md

@ -2,9 +2,9 @@
### Instructions
Write a function that returns the first prime number that is equal or inferior to the `int` passed as parameter.
Write a **function** which returns the first prime number which is equal or inferior to the `u64` passed as parameter.
If there are no primes inferior to the `int` passed as parameter the function should return 0.
If there are no primes inferior to the `u64` passed as parameter the function should return `0`.
### Expected function

32
subjects/queens/README.md

@ -2,23 +2,21 @@
### Instructions
In a chess game, a queen can attack pieces which are on the same row,
column, or diagonal.
In a chess game, a queen can attack pieces which are on the same row, column, or diagonal.
Your purpose in this exercise is to find out if two queens can attack
each other using the same rules.
The purpose of this exercise is to find out if two queens can attack each other using the same rules.
The chess board will be represented as an 8 by 8 array.
So, given the position of the two queens on a chess board, you will have to
implement the function `can_attack` in the given struct `Queen` with
the purpose of finding out if the two queens can attack each other or not.
the purpose of finding out whether the two queens can attack each other or not.
For this to be possible, you will also have to implement the struct `ChessPosition`
with the function `new` that will allow you to verify if the position is valid or not. If the position is valid it will return that position and if it is invalid it will return `None`.
with the function `new`. This will allow you to verify if the position is valid or not. If the position is valid it will return that position, otherwise it will return `None`.
So if you are told that the white queen is at (2, 3) and the black queen is at (5, 6),
then you would know you have got a set-up like so:
For example, if the white queen is at (2, 3) and the black queen is at (5, 6),
then the set-up would be like so:
```
_ _ _ _ _ _ _ _
@ -33,26 +31,30 @@ _ _ _ _ _ _ _ _
In this case, the two queens can attack each other because both pieces share a diagonal.
### Expected Function
### Expected Function and Structures
```rust
#[derive(Debug)]
pub struct ChessPosition {
rank: i32,
file: i32,
pub rank: i32,
pub file: i32,
}
#[derive(Debug)]
pub struct Queen {
position: ChessPosition,
pub position: ChessPosition,
}
impl ChessPosition {
pub fn new(rank: i32, file: i32) -> Option<Self> {}
pub fn new(rank: i32, file: i32) -> Option<Self> {
}
}
impl Queen {
pub fn can_attack(&self, other: &Queen) -> bool {}
pub fn can_attack(&self, other: &Queen) -> bool {
}
}
```
@ -61,8 +63,6 @@ impl Queen {
Here is a possible program to test your function :
```rust
use queens::queens;
fn main() {
let white_queen = Queen::new(ChessPosition::new(2, 2).unwrap());
let black_queen = Queen::new(ChessPosition::new(0, 4).unwrap());

11
subjects/reverse_it/README.md

@ -2,18 +2,19 @@
### Instructions
Create a function called `reverse_it` that takes a number and returns a string with the number backwards followed by the original number. If the number is negative you should
just add the char `-` to the beginning of the string.
Create a function called `reverse_it` that takes a number and returns a string with the number backwards followed by the original number. If the number is negative a char `-` has to be added to the beginning of the string.
### Expected Functions
```rust
fn reverse_it(v: i32) -> String {}
pub fn reverse_it(v: i32) -> String {
}
```
### Usage
Here is a program to test your function
Here is a program to test your function,
```rust
fn main() {
@ -22,7 +23,7 @@ fn main() {
}
```
And its output
And its output:
```console
student@ubuntu:~/[[ROOT]]/test$ cargo run

12
subjects/rot21/README.md

@ -2,17 +2,19 @@
### Instructions
Your purpose in this exercise is to create a `rot21` function that works like the ROT13 cipher.
The purpose of this exercise is to create a `rot21` function that works like the ROT13 cipher.
Your function will receive a string and it will rotate each letter of that string 21 times to the right.
This function will receive a `string` and it will rotate each letter of that `string` 21 times to the right.
Your function should only change letters. If the string includes punctuation, symbols and numbers
The function should only rotate letters. If the string includes punctuation, symbols and/or numbers
they will remain the same.
### Expected functions
```rust
pub fn rot21(input: &str) -> String {}
pub fn rot21(input: &str) -> String {
}
```
### Usage
@ -32,7 +34,7 @@ fn main() {
```
And its output
And its output:
```console
student@ubuntu:~/[[ROOT]]/test$ cargo run

27
subjects/rpn/README.md

@ -2,23 +2,19 @@
### Instructions
Write a program that takes a `string` which contains an equation written in
`Reverse Polish Notation` (RPN) as its first argument, that evaluates the equation, and that
prints the result on the standard output followed by a newline (`'\n'`).
Write a **program** which takes a `string` which contains an equation written in `Reverse Polish Notation` (RPN) as its first argument,
which evaluates the equation, and which prints the result on the standard output followed by a newline (`'\n'`).
`Reverse Polish Notation` is a mathematical notation in which every operator
follows all of its operands. In RPN, every operator encountered evaluates the
previous 2 operands, and the result of this operation then becomes the first of
the two operands for the subsequent operator. Operands and operators must be
spaced by at least one space.
`Reverse Polish Notation` is a mathematical notation in which every operator follows all of its operands. In RPN,
every operator encountered evaluates the previous 2 operands, and the result of this operation then becomes the first of
the two operands for the subsequent operator. Operands and operators must be spaced by at least one space.
The following operators must be implemented : `+`, `-`, `*`, `/`, and `%`.
If the `string` is not valid or if there is not exactly one argument, `Error` must be printed
on the standard output followed by a newline.
If the `string` is not valid or if there is not exactly one argument, `Error` must be printed on the standard output followed by a newline.
If the `string` has extra spaces it is still considered valid.
All the given operands must fit in a `int`.
All the given operands must fit in a `i64`.
Examples of formulas converted in RPN:
@ -30,7 +26,7 @@ Examples of formulas converted in RPN:
Here is how to evaluate a formula in RPN:
```
```console
1 2 * 3 * 4 -
2 3 * 4 -
6 4 -
@ -39,7 +35,7 @@ Here is how to evaluate a formula in RPN:
Or:
```
```console
3 1 2 * * 4 -
3 2 * 4 -
6 4 -
@ -64,10 +60,11 @@ $ cargo run "1 2 * 3 * 4 +"
10
$ cargo run "1 2 3 4 +"
Error
$ cargo run
$ cargo run ""
Error
$ cargo run " 1 3 * 2 -"
1
$ cargo run " 1 3 * ksd 2 -"
Error```
Error
```
````

Loading…
Cancel
Save