Browse Source

Merge pull request #997 from 01-edu/correction-of-quest-01-quest-02-quest-03-01-692

uodate rust readme, adding dependencies & clarifications
pull/1062/head
David Mata 2 years ago committed by GitHub
parent
commit
8fb64a025f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 18
      subjects/borrow_box/README.md
  2. 5
      subjects/borrow_me_the_reference/README.md
  3. 1
      subjects/box_recursion/README.md
  4. 28
      subjects/boxing_todo/README.md
  5. 3
      subjects/card_deck/README.md
  6. 2
      subjects/circle/README.md
  7. 8
      subjects/copy/README.md
  8. 8
      subjects/does_it_fit/README.md
  9. 8
      subjects/drop_the_thread/README.md
  10. 46
      subjects/error_types/README.md
  11. 4
      subjects/expected_variable/README.md
  12. 6
      subjects/generics/README.md
  13. 2
      subjects/handling/README.md
  14. 2
      subjects/hashing/README.md
  15. 16
      subjects/highest/README.md
  16. 1
      subjects/lalgebra_vector/README.md
  17. 4
      subjects/looping/README.md
  18. 8
      subjects/matrix/README.md
  19. 6
      subjects/matrix_mult/README.md
  20. 8
      subjects/panic/README.md
  21. 2
      subjects/profanity_filter/README.md
  22. 30
      subjects/sales/README.md
  23. 40
      subjects/shopping_mall/README.md
  24. 2
      subjects/slices_to_map/README.md
  25. 3
      subjects/spelling/README.md
  26. 2
      subjects/talking/README.md
  27. 14
      subjects/traits/README.md
  28. 6
      subjects/tuples/README.md
  29. 11
      subjects/unwrap_or_expect/README.md

18
subjects/borrow_box/README.md

@ -4,18 +4,18 @@
In this exercise, a **CRUD** functionality will have to be created. Therefore the following functions will have to be defined :
- `new`, which receives two players and initializes them with a name and a score. This functions should
- `new`, which receives two players and initializes them with a name and a score. This function should
return the structure wrapped in a Box.
- `read_winner`, which returns a tuple with the name and the score of the player who is winning.
In case none of the players are winning, it should return the same tuple with the string "Same score! tied" and the tied score.
- `update_score`, which receives the name of a player.
This function should increment the score of the player. The score should only be increased if it does not pass the `nbr_of_games`.
Example: if the nbr_of_games is 3 then the winner of the game should be the one who is the best out of three games. So if one play as 2 wins then
he is the winner and the function should not increase the score anymore for either players.
- `update_score`, which receives the name of a player.
This function should increment the score of the player. The score should only be increased if it does not pass the `nbr_of_games`.
Example: if the nbr_of_games is 3 then the winner of the game should be the one who is the best out of three games. So if one play has 2 wins then
he is the winner and the function should not increase the score anymore for either player.
- `delete`, which takes the ownership of the boxed game and returning a string : "Game deleted: id -> 0".
- `delete`, which takes the ownership of the boxed game and returns a string: "game deleted: id -> 0".
### Notions
@ -26,8 +26,12 @@ In this exercise, a **CRUD** functionality will have to be created. Therefore th
```rust
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Game {
// expected public fields
pub id: u32,
pub p1: (String, u16),
pub p2: (String, u16),
pub nbr_of_games: u16
}
impl Game {
pub fn new(i: u32, pl1: String, pl2: String, n: u16) -> Box<Game> {

5
subjects/borrow_me_the_reference/README.md

@ -31,6 +31,11 @@ pub fn is_correct(v: &mut Vec<&str>) -> usize {
- [ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html)
- [meval](https://docs.rs/meval/0.2.0/meval/)
### Dependencies
meval = "0.2"
### Usage
Here is a program to test your function

1
subjects/box_recursion/README.md

@ -15,7 +15,6 @@ Do not forget that this will be a recursion type and it must point to `None` if
### Notions
- [enum](https://doc.rust-lang.org/rust-by-example/custom_types/enum.html)
- [boc](https://doc.rust-lang.org/book/ch15-01-box.html)
- [Module std::option](https://doc.rust-lang.org/std/option/)

28
subjects/boxing_todo/README.md

@ -2,7 +2,7 @@
### Instructions
The objective is create an api to parse a list of _todos_ that is organized in a JSON file,
The objective is to create an api to parse a list of _todos_ that is organized in a JSON file,
handling all possible errors in a multiple error system.
Organization of the JSON file:
@ -17,9 +17,9 @@ Organization of the JSON file:
}
```
#### Error.rs
#### err.rs
Create a module in another file called **error.rs** which handles the boxing of errors.
Create a module in another file called **err.rs** which handles the boxing of errors.
This module must implement an `enum` called `ParseErr` which will take care of the
parsing errors. It must have the following elements:
@ -29,8 +29,8 @@ parsing errors. It must have the following elements:
A structure called `ReadErr` which will take care of the reading errors, having just an element called `child_err` of type `Box<dyn Error>`.
For each data structure you will have to implement a function called `fmt` for the trait `Display` which writes
out the message **"Failed to parse todo"** in case it is a parsing error. Otherwise, it should write the message
**"Failed to read todo file"**.
out the message **"Fail to parse todo"** in case it is a parsing error. Otherwise, it should write the message
**"Fail to read todo file"**.
For the `Error` trait the following functions (methods) have to be implemented:
- `source` which returns an `Option` with the error:
@ -54,7 +54,7 @@ Basically it must parse and read the JSON file and return the `TodoList` if ever
### Expected Functions
For **error.rs**
For **err.rs**
```rust
use std::fmt;
@ -99,23 +99,23 @@ impl Error for ReadErr {
for **lib.rs**
```rust
mod error;
use error::{ ParseErr, ReadErr };
mod err;
use err::{ ParseErr, ReadErr };
pub use json::{parse, stringify};
pub use std::error::Error;
#[derive(Debug, Eq, PartialEq)]
pub struct Task {
id: u32,
description: String,
level: u32,
pub id: u32,
pub description: String,
pub level: u32,
}
#[derive(Debug, Eq, PartialEq)]
pub struct TodoList {
title: String,
tasks: Vec<Task>,
pub title: String,
pub tasks: Vec<Task>,
}
impl TodoList {
@ -168,6 +168,6 @@ And its output:
$ cargo run
TodoList { title: "TODO LIST FOR PISCINE RUST", tasks: [Task { id: 0, description: "do this", level: 0 }, Task { id: 1, description: "do that", level: 5 }] }
Todo List parse failed: None
Fail to parses todo Some(Malformed(UnexpectedCharacter { ch: ',', line: 2, column: 18 }))
Fail to parse todo Some(Malformed(UnexpectedCharacter { ch: ',', line: 2, column: 18 }))
$
```

3
subjects/card_deck/README.md

@ -61,6 +61,9 @@ pub struct Card {
pub suit: Suit,
pub rank: Rank,
}
pub fn winner_card(car: Card) -> bool{
}
```
### Usage

2
subjects/circle/README.md

@ -28,7 +28,7 @@ Create the structures `Circle` and `Point` (which will be made of two coordinate
This snippets are incomplete and it is part of the exercise to discover how to complete them. In the [usage](#usage) you will find all the information that you need.
```rust
struct Circle {
pub struct Circle {
center //..
radius //..
}

8
subjects/copy/README.md

@ -25,13 +25,13 @@ The objective is to know how ownership works with different types.
### Expected Functions
```rust
pub fn nbr_function(c: u32) -> (u32, f64, f64) {
pub fn nbr_function(c: i32) -> (i32, f64, f64) {
}
pub fn str_function(a: String) -> (String, String) {
}
pub fn vec_function(b: Vec<u32>) -> (Vec<u32>, Vec<f64>) {
pub fn vec_function(b: Vec<i32>) -> (Vec<i32>, Vec<f64>) {
}
```
@ -43,7 +43,7 @@ Here is a possible program to test your function :
use copy::*;
fn main() {
let a: u32 = 0;
let a: i32 = 0;
let b = String::from("1 2 4 5 6");
let c = vec![1, 2, 4, 5];
@ -61,7 +61,7 @@ And its output:
```console
$ cargo run
(0, 1.0, inf)
(0, 1.0, -inf)
("1 2 4 5 6", "2.718281828459045 7.38905609893065 54.598150033144236 148.4131591025766 403.4287934927351")
([1, 2, 4, 5], [0.0, 0.6931471805599453, 1.3862943611198906, 1.6094379124341003])
$

8
subjects/does_it_fit/README.md

@ -6,7 +6,7 @@ Using the `areas_volumes` module provided, create two **functions**:
- `area_fit` which receives 6 arguments and returns a boolean:
- `x` and `y`, length and width of the square in which it is going to be tried to fit the geometrical shapes (both usize)
- `x` and `y`, length and width of the Rectangle in which it is going to be tried to fit the geometrical shapes (both usize)
- `objects`, the type of geometrical shape(s) which are going to be tried to be fitted in the square (areas_volumes::GeometricalShapes)
- `times`, the number of geometrical shapes which are going to be tried to be fitted in the square (usize)
- `a` and `b`, the dimensions which the plane(s) shape(s) passed will have (both usize)
@ -20,7 +20,7 @@ Using the `areas_volumes` module provided, create two **functions**:
- `objects`, the type of geometrical volume(s) which are going to be tried to be fitted in the box (areas_volumes::GeometricalVolumes)
- `times`, the number of geometrical volumes which are going to be tried to be fitted in the box (usize)
- `a`, `b` and `c`, the dimensions which the geometrical volume(s) passed will have (all of them usize)
- `a` will refer to the side of the Cube, the radius of the Sphere, the side_a of the Parallelepipede, the area of the base of the Triangular Pyramid or the base radius of the Cone
- `a` will refer to the side of the Cube, the radius of the Sphere, the side_a of the Parallelepiped, the area of the base of the Triangular Pyramid or the base radius of the Cone
- `b` will refer to the side_b of the Parallelepiped, the height of the Triangular Pyramid or the height of the Cone
- `c` will refer to the side_c of the Parallelepiped
- `volume_fit` should return `true` if the geometrical volume(s) fit inside of the box.
@ -128,7 +128,7 @@ fn main() {
volume_fit(5, 5, 5, GeometricalVolumes::Sphere, 3, 2, 0, 0)
);
println!(
"Do 3 triangles (5 base and 3 height) fit in a 5 by 7 by 5 box? {}",
"Does 1 parallelepiped (6 base, 7 height and depth 4) fit in a 5 by 7 by 5 parallelepiped? {}",
volume_fit(5, 7, 5, GeometricalVolumes::Parallelepiped, 1, 6, 7, 4)
);
}
@ -141,6 +141,6 @@ $ cargo run
Do 100 rectangles (2x1) fit in a 2 by 4 square? false
Do 3 triangles (5 base and 3 height) fit in a 5 by 5 square? true
Do 3 spheres (2 radius) fit in a 5 by 5 by 5 box? true
Do 3 triangles (5 base and 3 height) fit in a 5 by 7 by 5 box? true
Does 1 parallelepiped (6 base, 7 height and depth 4) fit in a 5 by 7 by 5 parallelepiped? true
$
```

8
subjects/drop_the_thread/README.md

@ -17,15 +17,15 @@ in this exercise a Drop checker API has to be created. For this you must define:
- `cmd`, the name of the thread.
- `parent`, that will be the link to the structure `Workers` (Tip: this must be a reference to the structure Workers)
- Implementation of each structure:
- Implementation of each structure:state
- `Workers` :
- `new`, that creates a default worker
- `new_worker`, that returns a tuple with the `pid` and a new `Thread`,
this function must receive a `String` being the `cmd`
- `is_dropped`, that receives a `pid` and returns a `bool` that indicates the state of the thread by using the `pid`
- `track_worker`, it should return a `usize`, that will be the last available index of the `states` vector, being the new next thread
- `is_dropped`, that receives a `pid` and returns a `bool` that indicates the state of the thread by using the `pid`
- `track_worker`, it should return a `usize`, that will be the last available index of the `states` vector, being the new next thread
- `add_drop`, this function must be **called by the `Drop` trait**. It will receive a `pid` that will be used to change the
state of the thread. If the state of that thread is `true` then it will panic with the message ("Cannot drop {}, because its already dropped", pid).
Otherwise it should change the state to true and increment the `drops` field by one.
@ -50,7 +50,7 @@ use std::cell::{RefCell, Cell};
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct Workers {
pub drops: Cell<usize>,
pub state: RefCell<Vec<bool>>
pub states: RefCell<Vec<bool>>
}
impl Workers {

46
subjects/error_types/README.md

@ -18,7 +18,7 @@ Create a structure called `Form` that will have the following fields:
- `first_name`, that will be a string
- `last_name`, that will be a string
- `birth`, of type `NaiveDate` that will convert a string "2015-09-05" to a date of that format
- `sex`, SexType that must be a `enum` with the fields `Male` and `Female`
- `fav_colour`, of type Color that must be a `enum` with the fields `Red`, `Blue` and `Green`
- `birth_location`, that will be a string
- `password`, that will be a string
@ -44,6 +44,12 @@ ex: ("password", "asdaSD\_")
- [Error types](https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/define_error_type.html)
- [Struct NaiveDate](https://docs.rs/chrono/0.4.19/chrono/naive/struct.NaiveDate.html)
### Dependencies
chrono = "0.4"
### Expected Function
```rust
@ -59,21 +65,24 @@ impl FErr {
}
#[derive(Debug, Eq, PartialEq)]
pub enum SexType {
// expected public fields
pub enum Color {
}
#[derive(Debug, Eq, PartialEq)]
pub struct Form {
// expected public fields
}
impl Form {
pub fn new(first_name: String,
last_name: String,
birth: NaiveDate,
sex: SexType,
birth_location: String,
password: String) -> Form {}
pub fn new(
first_name: String,
last_name: String,
birth: NaiveDate,
fav_colour: Color,
birth_location: String,
password: String,
) -> Form {}
pub fn validate(&self) -> Result<Vec<&str>, FErr> {}
}
```
@ -87,12 +96,13 @@ use error_types::*;
fn main() {
let mut form_output = Form::new(
String::from("Alice"),
String::from("Bear"),
String::from("Lee"),
String::from("Silva"),
create_date("2015-09-05"),
SexType::Male,
Color::Red,
String::from("Africa"),
String::from("qwqwsa1dty_"));
String::from("qwqwsa1dty_"),
);
println!("{:?}", form_output);
println!("{:?}", form_output.validate().unwrap());
@ -116,11 +126,11 @@ And its output:
```console
$ cargo run
Form { first_name: "Lee", last_name: "Silva", birth: 2015-09-05, sex: Male, birth_location: "Africa", password: "qwqwsa1dty_" }
Form { first_name: "Lee", last_name: "Silva", birth: 2015-09-05, fav_colour: Red, birth_location: "Africa", password: "qwqwsa1dty_" }
["Valid first name", "Valid password"]
FErr { form_values: ("first_name", ""), date: "2020-12-28 13:29:11", err: "No user name" }
FErr { form_values: ("password", "dty_1"), date: "2020-12-28 13:29:11", err: "At least 8 characters" }
FErr { form_values: ("password", "asdasASd(_"), date: "2020-12-28 13:29:11", err: "Combination of different ASCII character types (numbers, letters and none alphanumeric characters)" }
FErr { form_values: ("password", "asdasASd123SA"), date: "2020-12-28 13:29:11", err: "Combination of different ASCII character types (numbers, letters and none alphanumeric characters)" }
FErr { form_values: ("first_name", ""), date: "2022-04-21 09:18:12", err: "No user name" }
FErr { form_values: ("password", "dty_1"), date: "2022-04-21 09:18:12", err: "At least 8 characters" }
FErr { form_values: ("password", "asdasASd(_"), date: "2022-04-21 09:18:12", err: "Combination of different ASCII character types (numbers, letters and none alphanumeric characters)" }
FErr { form_values: ("password", "asdasASd123SA"), date: "2022-04-21 09:18:12", err: "Combination of different ASCII character types (numbers, letters and none alphanumeric characters)" }
$
```

4
subjects/expected_variable/README.md

@ -50,9 +50,9 @@ And its output:
```sh
$ cargo run
100% close to ir
100% close to it
88% close to it
None
73% close to it
67% close to it
$
```

6
subjects/generics/README.md

@ -4,6 +4,12 @@
Write a **function** called `identity` which calculates the identity of a value (receives any data type and returns the same value).
### Notions
- [Generics](https://doc.rust-lang.org/book/ch10-01-syntax.html)
### Expected Function (signature to be completed)
```rust

2
subjects/handling/README.md

@ -19,7 +19,7 @@ In case something goes wrong, it should panic, with the error.
### Expected Function
```rust
pub fn open_or_create(s: &str, content: &str) {
pub fn open_or_create(file: &str, content: &str) {
}
```

2
subjects/hashing/README.md

@ -6,7 +6,7 @@ Given a list of integers (Vec<i32>) write three **functions**.
Write a **function** called `mean` that calculates the `mean` (the average value) of all the values in the list.
Write a **function** called `median` that calculates the `median` (for a sorted list, it is the value in the middle).
Write a **function** called `median` that calculates the `median` (for a sorted list, it is the value in the middle). If there is an even amount of numbers in the list, the middle pair must be determined, added together, and divided by two to find the median value.
Write a **function** called `mode` that calculates the mode (the value
that appears more often).

16
subjects/highest/README.md

@ -21,13 +21,13 @@ These methods have to be written:
```rust
pub fn new(&[u32]) -> Self {}
pub fn List(&self) -> &[u32] {}
pub fn list(&self) -> &[u32] {}
pub fn Latest(&self) -> Option<u32> {}
pub fn latest(&self) -> Option<u32> {}
pub fn Highest(&self) -> Option<u32> {}
pub fn highest(&self) -> Option<u32> {}
pub fn Highest_Three(&self) -> Vec<u32> {}
pub fn highest_three(&self) -> Vec<u32> {}
```
### Usage
@ -45,10 +45,10 @@ struct Numbers<'a> {
fn main() {
let expected = [30, 500, 20, 70];
let n = Numbers::new(&expected);
println!("{:?}", n.List());
println!("{:?}", n.Highest());
println!("{:?}", n.Latest());
println!("{:?}", n.Highest_Three());
println!("{:?}", n.list());
println!("{:?}", n.highest());
println!("{:?}", n.latest());
println!("{:?}", n.highest_three());
}
```

1
subjects/lalgebra_vector/README.md

@ -29,6 +29,7 @@ impl Vector<T> {
}
pub fn dot(&self, other: &Self) -> Option<T> {
}
}
```

4
subjects/looping/README.md

@ -4,7 +4,7 @@
Write a **program** that prints a riddle, receives input from the user and checks that the answer is correct.
The program must allow indefinite number of trials and only quit after the correct answer is given.
The program must allow an indefinite number of trials and only quit after the correct answer is given.
Every time the user introduces an incorrect answer the program must print the riddle again and after the user gives the correct answer the program must print the number of tries that took to get the correct answer.
@ -17,7 +17,7 @@ Answer: The letter e
- [Moduler std::io](https://doc.rust-lang.org/std/io/index.html)
- [loop](https://doc.rust-lang.org/std/keyword.loop.html)
### Usage
### Usage 
```console
$ cargo run

8
subjects/matrix/README.md

@ -8,13 +8,15 @@ Define a data structure to represent a matrix of any size and implement the basi
- You have to use the definition of scalars done in the exercise: `lalgebra_scalar`
- Then define the associated function `identity` that returns the identity matrix of size n
- Define `new` that returns a matrix of size `1 x 1`
- Finally, define the associated function `zero` that returns a matrix of size `row x col` with all the positions filled by zeroes
- Then define the associated function `identity` that returns the identity matrix of size n
- Finally, define the associated function `zero` that returns a matrix of size `row x col` with all the positions filled by zeros
### Notions
[Traits](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html)
- [Traits](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html)
### Expected Functions and Structure

6
subjects/matrix_mult/README.md

@ -10,7 +10,7 @@ Implement the methods:
- `row(n)` which returns the `n`th row in the matrix.
- `col(n)` which returns the `n`th
- `col(n)` which returns the `n`th column in the matrix.
Define the matrix multiplication by implementing the std::ops::Mul for the type matrix
@ -21,10 +21,10 @@ impl Matrix<T> {
pub fn number_of_cols(&self) -> usize {
}
pub fn rows(&self) -> usize {
pub fn number_of_rows(&self) -> usize {
}
pub fn number_of_row(&self, n: usize) -> Vec<T> {
pub fn rows(&self, n: usize) -> Vec<T> {
}
pub fn col(&self, n: usize) -> Vec<T> {

8
subjects/panic/README.md

@ -5,8 +5,6 @@
Write a **function** that tries to open a file and panics if the file
does not exist.
### Notions
### Expected Function
```rust
@ -27,9 +25,14 @@ use panic::*;
fn main() {
let filename = "created.txt";
File::create(filename).unwrap();
let a = open_file(filename);
println!("{:?}", a);
fs::remove_file(filename).unwrap();
//It must panic
let b = open_file(filename);
}
```
@ -38,5 +41,6 @@ And its output:
```console
$ cargo run
File { fd: 3, path: "panic/a.txt", read: true, write: false }
thread 'main' panicked at 'File not found'
$
```

2
subjects/profanity_filter/README.md

@ -18,7 +18,7 @@ The `struct` must also have an implementation of 2 **functions** associated with
- `send_ms`, which only has its implementation type (**self**) as argument and returns an option:
- This function must return `None` if the content of the message is either **empty** or contains the word **stupid**. Otherwise it returns the content of the message.
You will have to create two more **functions** that are not associated with any structure:
You will have to create one more **function** that is not associated with any structure:
- `check_ms` which:
- receives as parameters the reference to the structure `Message`

30
subjects/sales/README.md

@ -5,11 +5,19 @@
In this exercise a shopping system will have to be created. There will be :
- A store that will save all the products in it
- A cart that will have `items`, that the client will buy, and a `receipt`
- A cart that will have `items` that the client will buy, and a `receipt`
This store is having a promotion, "Buy three and get one for free" (the free item must be the cheapest). The receipt must not present
any value as 0, so the promotion must be a reduction to be applied to all items instead.(see the example)
You will have to implement for the Cart structure the following **functions**:
- `new`, that will initialize the cart
- `insert_item`, that will receive a reference to `Store` and a `String`. Just like the name says you will
have to insert the item to the cart
- `generate_receipt`, that returns a vector of sorted floats. This function must generate the receipt just
like the example above, using the promotion. Also saving the result in the filed `receipt`.
### Notions
- [closures](https://doc.rust-lang.org/rust-by-example/fn/closures.html)
@ -17,8 +25,7 @@ any value as 0, so the promotion must be a reduction to be applied to all items
### Expected Function
```rust
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq)]
pub struct Store {
pub products: Vec<(String, f32)>,
}
@ -28,43 +35,34 @@ impl Store {
}
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq)]
pub struct Cart {
// expected public fields
}
impl Cart {
pub fn new() -> Cart {}
pub fn insert_item(&mut self, s: &Store, ele: String) {}
pub fn get_prices(&self) -> Vec<f32> {}
pub fn generate_receipt(&mut self) -> Vec<f32> {}
}
```
### Example
`[1.23, 3.12, 23.1]` -> the receipt will be `[1.17, 2.98, 22.07]`
So `1.17 + 2.98 + 22.07 == 3.12 + 23.1 + 0`
Because `1.17 + 2.98 + 22.07 == 0 + 3.12 + 23.1`
This is a percentage calculation, and it can be applied to a set of three items.
If the client purchase 9 items, the promotion will be applied, three for free, to all items
|--------------| |---------------| |---------------|
`[1.23, 23.1, 3.12, 9.75, 1.75, 23.75, 2.75, 1.64, 15.23]` -> the receipt will be `[1.16, 1.55, 1.65, 2.6, 2.94, 9.2, 14.38, 21.8, 22.42]`
|--------| |--------| |--------|
`[3.12, 9.75, 1.75, 23.75, 2.75, 1.64, 15.23]` -> the receipt will be `[1.54, 1.65, 2.59, 2.94, 9.18, 14.34, 22.36]`
and so on... (hint: Closures is the way)
You will have to implement for the Cart structure the following **functions**:
- `new`, that will initialize the cart
- `insert_item`, that will receive a reference to `Store` and a `String`. Just like the name says you will
have to insert the item to the cart
- `generate_receipt`, that returns a vector of sorted floats. This function must generate the receipt just
like the example above, using the promotion. Also saving the result in the filed `receipt`.
### Usage

40
subjects/shopping_mall/README.md

@ -6,10 +6,10 @@ Using the `mall` module provided create the following **functions** to help run
- `biggest_store`: receives a `mall::Mall` and returns the `Store` with the biggest `square_meters`;
- `highest_paid_employees`: receives a `mall::Mall` and returns a vector containing the `Employee`(s) with the highest salaries;
- `nbr_of_employees`: receives a `mall::Mall` and returns the number of employees and securities, as a `usize`, in that mall.
- `fire_old_securities`: receives a `mall::Mall` and removes from the `mall::Mall.securities` all securities who are 50 years old or older.
- `check_for_securities`: receives a `mall::Mall` and a vector of `Security` and, if there is not at least 1 security for every 200 square meters of floor size, a security should be added to the `mall::Mall.securities`
- `cut_or_raise`: receives a `mall::Mall` and raises or cuts, the salary of every employee in the mall by 10%, if the employee works for more than 10 hours
- `nbr_of_employees`: receives a `mall::Mall` and returns the number of employees and guards, as a `usize`, in that mall;
- `fire_old_guards`: receives a `mall::Mall` and removes from the `mall::Mall.guards` all guards who are 50 years old or older;
- `check_for_guards`: receives a `mall::Mall` and a vector of `Guard` and, if there is not at least 1 guard for every 200 square meters of floor size, a guard should be added to the `mall::Mall.guards`;
- `cut_or_raise`: receives a `mall::Mall` and raises or cuts, the salary of every employee in the mall by 10%, if the employee works for more than 10 hours (consider that the guards are not employees from the mall).
### Expected Function
@ -21,16 +21,16 @@ Using the `mall` module provided create the following **functions** to help run
#[derive(Debug, Clone, PartialEq)]
pub struct Mall {
pub name: String,
pub securities: Vec<security::Security>,
pub guards: Vec<guard::Guard>,
pub floors: Vec<floor::Floor>,
}
impl Mall {
#[allow(dead_code)]
pub fn new(name: &str, securities: Vec<security::Security>, floors: Vec<floor::Floor>) -> Mall {
pub fn new(name: &str, guards: Vec<guard::Guard>, floors: Vec<floor::Floor>) -> Mall {
Mall {
name: name.to_string(),
securities: securities,
guards: guards,
floors: floors,
}
}
@ -41,29 +41,29 @@ impl Mall {
}
#[allow(dead_code)]
pub fn hire_security(&mut self, security: security::Security) {
self.securities.push(security);
pub fn hire_guards(&mut self, guard: guard::Guard) {
self.guards.push(guard);
}
#[allow(dead_code)]
pub fn fire_security(&mut self, name: String) {
self.securities.retain(|x| x.name != name);
pub fn fire_guards(&mut self, name: String) {
self.guards.retain(|x| x.name != name);
}
}
pub mod security {
pub mod guard {
#[derive(Debug, Clone, PartialEq)]
pub struct Security {
pub struct Guard {
pub name: String,
pub age: u8,
pub years_experience: u8,
}
impl Security {
impl Guard {
#[allow(dead_code)]
pub fn new(name: &str, age: u8, years_experience: u8) -> Security {
Security {
pub fn new(name: &str, age: u8, years_experience: u8) -> Guard {
Guard {
name: name.to_string(),
age: age,
years_experience: years_experience,
@ -210,9 +210,9 @@ use shopping_mall::*;
fn main() {
let secs = vec![
mall::security::Security::new("John Oliver", 34, 7),
mall::security::Security::new("Logan West", 23, 2),
mall::security::Security::new("Bob Schumacher", 53, 15),
mall::guard::Guard::new("John Oliver", 34, 7),
mall::guard::Guard::new("Logan West", 23, 2),
mall::guard::Guard::new("Bob Schumacher", 53, 15),
];
let footzo_emp = vec![
@ -288,6 +288,6 @@ And its ouput:
```rs
$ cargo run
Mall { name: "La Vie Funchal", securities: [Security { name: "John Oliver", age: 34, years_experience: 7 }, Security { name: "Logan West", age: 23, years_experience: 2 }, Security { name: "Bob Schumacher", age: 53, years_experience: 15 }], floors: [Floor { name: "Ground Floor", stores: [Store { name: "Footzo", square_meters: 50, employees: [Employee { name: "Finbar Haines", age: 36, working_hours: (9, 14), salary: 650.88 }, Employee { name: "Roksanna Rocha", age: 45, working_hours: (13, 22), salary: 772.0 }, Employee { name: "Sienna-Rose Penn", age: 26, working_hours: (9, 22), salary: 1000.43 }] }, Store { name: "Swashion", square_meters: 43, employees: [Employee { name: "Abdallah Stafford", age: 54, working_hours: (8, 22), salary: 1234.21 }, Employee { name: "Marian Snyder", age: 21, working_hours: (8, 14), salary: 831.9 }, Employee { name: "Amanda Mclean", age: 29, working_hours: (13, 22), salary: 1222.12 }, Employee { name: "Faizaan Castro", age: 32, working_hours: (11, 18), salary: 1106.43 }] }], size_limit: 300 }, Floor { name: "Food Floor", stores: [Store { name: "PizBite", square_meters: 60, employees: [Employee { name: "Juniper Cannon", age: 21, working_hours: (16, 23), salary: 804.35 }, Employee { name: "Alena Simon", age: 28, working_hours: (9, 15), salary: 973.54 }, Employee { name: "Yasemin Collins", age: 29, working_hours: (9, 19), salary: 986.33 }, Employee { name: "Areeb Roberson", age: 54, working_hours: (9, 22), salary: 957.82 }, Employee { name: "Rocco Amin", age: 44, working_hours: (13, 23), salary: 689.21 }] }, Store { name: "Chillout Grill", square_meters: 50, employees: [Employee { name: "Rhian Crowther", age: 45, working_hours: (9, 15), salary: 841.18 }, Employee { name: "Nikkita Steadman", age: 52, working_hours: (14, 22), salary: 858.61 }, Employee { name: "Reginald Poole", age: 32, working_hours: (9, 22), salary: 1197.64 }, Employee { name: "Minnie Bull", age: 54, working_hours: (14, 22), salary: 1229.73 }] }, Store { name: "Sumo Food", square_meters: 30, employees: [Employee { name: "Chantelle Barajas", age: 20, working_hours: (8, 22), salary: 969.22 }, Employee { name: "Hywel Rudd", age: 49, working_hours: (12, 22), salary: 695.74 }, Employee { name: "Marianne Beasley", age: 55, working_hours: (8, 14), salary: 767.83 }] }], size_limit: 500 }, Floor { name: "Supermarket", stores: [Store { name: "Pretail", square_meters: 950, employees: [Employee { name: "Amara Schaefer", age: 23, working_hours: (9, 14), salary: 796.21 }, Employee { name: "Yara Wickens", age: 39, working_hours: (9, 14), salary: 853.42 }, Employee { name: "Tomi Boyer", age: 64, working_hours: (9, 14), salary: 881.83 }, Employee { name: "Greta Dickson", age: 42, working_hours: (9, 14), salary: 775.1 }, Employee { name: "Caroline Finnegan", age: 41, working_hours: (9, 14), salary: 702.92 }, Employee { name: "Indiana Baxter", age: 33, working_hours: (13, 20), salary: 991.71 }, Employee { name: "Jadine Page", age: 48, working_hours: (13, 20), salary: 743.21 }, Employee { name: "Husna Ryan", age: 43, working_hours: (13, 20), salary: 655.75 }, Employee { name: "Tyler Hunt", age: 63, working_hours: (13, 20), salary: 668.25 }, Employee { name: "Dahlia Caldwell", age: 56, working_hours: (13, 20), salary: 781.38 }, Employee { name: "Chandler Mansell", age: 20, working_hours: (19, 24), salary: 656.75 }, Employee { name: "Mohsin Mcgee", age: 30, working_hours: (19, 24), salary: 703.83 }, Employee { name: "Antoine Goulding", age: 45, working_hours: (19, 24), salary: 697.12 }, Employee { name: "Mark Barnard", age: 53, working_hours: (19, 24), salary: 788.81 }] }], size_limit: 1000 }] }
Mall { name: "La Vie Funchal", guards: [Guard { name: "John Oliver", age: 34, years_experience: 7 }, Guard { name: "Logan West", age: 23, years_experience: 2 }, Guard { name: "Bob Schumacher", age: 53, years_experience: 15 }], floors: [Floor { name: "Ground Floor", stores: [Store { name: "Footzo", square_meters: 50, employees: [Employee { name: "Finbar Haines", age: 36, working_hours: (9, 14), salary: 650.88 }, Employee { name: "Roksanna Rocha", age: 45, working_hours: (13, 22), salary: 772.0 }, Employee { name: "Sienna-Rose Penn", age: 26, working_hours: (9, 22), salary: 1000.43 }] }, Store { name: "Swashion", square_meters: 43, employees: [Employee { name: "Abdallah Stafford", age: 54, working_hours: (8, 22), salary: 1234.21 }, Employee { name: "Marian Snyder", age: 21, working_hours: (8, 14), salary: 831.9 }, Employee { name: "Amanda Mclean", age: 29, working_hours: (13, 22), salary: 1222.12 }, Employee { name: "Faizaan Castro", age: 32, working_hours: (11, 18), salary: 1106.43 }] }], size_limit: 300 }, Floor { name: "Food Floor", stores: [Store { name: "PizBite", square_meters: 60, employees: [Employee { name: "Juniper Cannon", age: 21, working_hours: (16, 23), salary: 804.35 }, Employee { name: "Alena Simon", age: 28, working_hours: (9, 15), salary: 973.54 }, Employee { name: "Yasemin Collins", age: 29, working_hours: (9, 19), salary: 986.33 }, Employee { name: "Areeb Roberson", age: 54, working_hours: (9, 22), salary: 957.82 }, Employee { name: "Rocco Amin", age: 44, working_hours: (13, 23), salary: 689.21 }] }, Store { name: "Chillout Grill", square_meters: 50, employees: [Employee { name: "Rhian Crowther", age: 45, working_hours: (9, 15), salary: 841.18 }, Employee { name: "Nikkita Steadman", age: 52, working_hours: (14, 22), salary: 858.61 }, Employee { name: "Reginald Poole", age: 32, working_hours: (9, 22), salary: 1197.64 }, Employee { name: "Minnie Bull", age: 54, working_hours: (14, 22), salary: 1229.73 }] }, Store { name: "Sumo Food", square_meters: 30, employees: [Employee { name: "Chantelle Barajas", age: 20, working_hours: (8, 22), salary: 969.22 }, Employee { name: "Hywel Rudd", age: 49, working_hours: (12, 22), salary: 695.74 }, Employee { name: "Marianne Beasley", age: 55, working_hours: (8, 14), salary: 767.83 }] }], size_limit: 500 }, Floor { name: "Supermarket", stores: [Store { name: "Pretail", square_meters: 950, employees: [Employee { name: "Amara Schaefer", age: 23, working_hours: (9, 14), salary: 796.21 }, Employee { name: "Yara Wickens", age: 39, working_hours: (9, 14), salary: 853.42 }, Employee { name: "Tomi Boyer", age: 64, working_hours: (9, 14), salary: 881.83 }, Employee { name: "Greta Dickson", age: 42, working_hours: (9, 14), salary: 775.1 }, Employee { name: "Caroline Finnegan", age: 41, working_hours: (9, 14), salary: 702.92 }, Employee { name: "Indiana Baxter", age: 33, working_hours: (13, 20), salary: 991.71 }, Employee { name: "Jadine Page", age: 48, working_hours: (13, 20), salary: 743.21 }, Employee { name: "Husna Ryan", age: 43, working_hours: (13, 20), salary: 655.75 }, Employee { name: "Tyler Hunt", age: 63, working_hours: (13, 20), salary: 668.25 }, Employee { name: "Dahlia Caldwell", age: 56, working_hours: (13, 20), salary: 781.38 }, Employee { name: "Chandler Mansell", age: 20, working_hours: (19, 24), salary: 656.75 }, Employee { name: "Mohsin Mcgee", age: 30, working_hours: (19, 24), salary: 703.83 }, Employee { name: "Antoine Goulding", age: 45, working_hours: (19, 24), salary: 697.12 }, Employee { name: "Mark Barnard", age: 53, working_hours: (19, 24), salary: 788.81 }] }], size_limit: 1000 }] }
$
```

2
subjects/slices_to_map/README.md

@ -2,7 +2,9 @@
### Instructions:
Create a function that borrows two slices and returns a hashmap where the first slice represents the keys and the second represents the values.
- If the slices have different sizes, the function should return the hashmap with the size of the smallest list.
### Expected Function

3
subjects/spelling/README.md

@ -22,9 +22,6 @@ Only positive numbers will be tested. (Up to a million).
- [patterns](https://doc.rust-lang.org/book/ch18-00-patterns.html)
### Dependencies
rand = "0.7"
### Expected function

2
subjects/talking/README.md

@ -8,7 +8,7 @@ His answers will be created by you following the rules below.
- He answers "There is no need to yell, calm down!" if you yell at him, for example "LEAVE ME ALONE!"
(it is considered yelling when the sentence is all written in capital letters).
- He answers "Sure" if you ask him something without yelling, for example "Is everything ok with you?"
- He answers "Sure." if you ask him something without yelling, for example "Is everything ok with you?"
- He answers "Quiet, I am thinking!" if you yell a question at him. "HOW ARE YOU?"
- He says "Just say something!" if you address him without actually saying anything.
- He answers "Interesting" to anything else.

14
subjects/traits/README.md

@ -6,10 +6,10 @@ Imagine you are designing a new video game and you have to create food that the
There are two types of food for now:
- Fruit: increase the strength by 4 unit per each kilogram of fruit consumed.
- Meat: has the weight in kilograms -> `weight_in_kg` (which is the weight of the whole piece) and the fat_content which corresponds to the percentage of the weight which is pure fat (the rest is consider protein) each kilogram of protein gives 4 units of `strenght` and each kilogram of fat gives 9 units of `strength`.
- Fruit: increase the strength by 4 units per each kilogram of fruit consumed.
- Meat: has the weight in kilograms `weight_in_kg` (which is the weight of the whole piece) and the `fat_content` which corresponds to the percentage of the weight which is pure fat (the rest is considered protein) each kilogram of protein gives 4 units of `strength` and each kilogram of fat gives 9 units of `strength`.
Define the `Food` trait for `Fruit` and `Meat`. The method require method `gives()` represents the energy that the food provides.
Define the `Food` trait for `Fruit` and `Meat`. The required method `gives()` represents the energy that the food provides.
Implement the `std::fmt::Display` trait for `Player` structure in a way that when using the template `{}` inside a println! macro it will print:
@ -17,6 +17,12 @@ Implement the `std::fmt::Display` trait for `Player` structure in a way that whe
- In the second line the strength, score and the money
- In the third line the weapons
### Notions
- [Traits](https://doc.rust-lang.org/book/ch10-02-traits.html)
### Expected Functions and Structures
```rust
@ -45,7 +51,7 @@ impl Player {
}
pub trait Food {
fn gives(&self) -> u32;
fn gives(&self) -> f64;
}
impl Food for Fruit {

6
subjects/tuples/README.md

@ -4,7 +4,7 @@
- Define a tuple structure to represent a `Student`.
- Each student is identified by an id number of type i32, his/her name and his/her last name as a string Print the content of the tuple to stdout
- Each student is identified by an id number of type i32, his/her name and his/her last name of type string.
- Then define three **functions** to return the id, first name and last name.
@ -22,6 +22,10 @@
- [Chapter 7](https://doc.rust-lang.org/stable/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html)
### Dependencies
meval = "0.2"
### Expected Functions
```rust

11
subjects/unwrap_or_expect/README.md

@ -2,19 +2,20 @@
### Instructions
A **function** called **odd_to_even** will be given, which returns a `Result`. If an error occurs the function will
return a tuple with a string, stating the error, and a vector with the elements which causing the error.
A **function** called **odd_to_even** will be given, which returns a `Result`. If there is an even value in the vector, the function will
return a tuple with a string, stating the error, and a vector with the elements that caused the error.
The objective is to execute the `odd_to_even` function and handle the error returned by it.
Create the following functions which receives a vector :
Create the following functions which receive a vector:
- `expect` which returns the error adding the string "ERROR "
- `unwrap_or` which in case of error returns an empty vector
- `unwrap_err` which returns error if its `Ok` and returns the
- `unwrap_err` which panics if the value is `Ok` and returns the
string containing the error in case of `Err`
- `unwrap` which unwraps the `Result`
- `unwrap_or_else` which in case of error returns the vector of elements which causes the error
- `unwrap_or_else` which in case of error returns the vector of elements that caused the error
### Notions

Loading…
Cancel
Save