Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 25 additions & 27 deletions subjects/borrow_box/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ Game time.

You will implement some **CRUD** functionality for a game session. You will need to implement the `GameSession` structure with the following associated functions:

- `new`: which initializes a game session state with player names and some other information. This function returns the structure wrapped in a `Box`.
- `new`: which initializes a game session state with player names and some other information.

- `read_winner`: which returns a tuple with the name and score of the player who is currently winning. In the case that no player is winning, it should return the same tuple with the string `"Same score! tied"` and the tied score.
- `read_winner`: which returns a tuple referencing the player who is currently winning. In the case that no player is winning, it should return `None`.

- `update_score`: which receives the name of a player, and increments their score. This function should **do nothing** if the the game session is already finished or if the name received doesn't match any player.

- `delete`: which takes ownership of the boxed game session and returns a string: `"game deleted: id -> 0"`, where `0` is the id of the `GameSession`.
- `delete`: which takes ownership of the game session and returns a string: `"game deleted: id -> {id}"`, where `{id}` is the id of the `GameSession`.

> Examples for `nb_games`:
>
Expand All @@ -25,23 +25,26 @@ You will implement some **CRUD** functionality for a game session. You will need
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct GameSession {
pub id: u32,
pub p1: (String, u16),
pub p2: (String, u16),
pub nb_games: u16
pub p1: (String, u32),
pub p2: (String, u32),
pub nb_games: u32,
}

impl GameSession {
pub fn new(id: u32, p1_name: String, p2_name: String, nb_games: u16) -> Box<GameSession> {

pub fn new(id: u32, p1_name: String, p2_name: String, nb_games: u32) -> GameSession {
todo!()
}
pub fn read_winner(&self) -> (String, u16) {

pub fn read_winner(&self) -> Option<&(String, u32)> {
todo!()
}
pub fn update_score(&mut self, user_name: String) {

pub fn update_score(&mut self, user_name: &str) {
todo!()
}
pub fn delete(self) -> String {

pub fn delete(self) -> String {
todo!()
}
}
```
Expand All @@ -56,38 +59,33 @@ use borrow_box::*;
fn main() {
let mut game = GameSession::new(0, String::from("Joao"), String::from("Susana"), 5);
println!("{:?}", game.read_winner());
// output : ("Same score! tied", 0)

game.update_score(String::from("Joao"));
game.update_score(String::from("Joao"));
game.update_score(String::from("Susana"));
game.update_score(String::from("Susana"));
game.update_score("Joao");
game.update_score("Joao");
game.update_score("Susana");
game.update_score("Susana");
println!("{:?}", game.read_winner());
// output : ("Same score! tied", 2)

game.update_score(String::from("Joao"));
// this one will not count because it already 5 games played, the nb_games
game.update_score(String::from("Susana"));
game.update_score("Joao");
// This one will not count because it already 5 games played, the `nb_games`
game.update_score("Susana");

println!("{:?}", game.read_winner());
// output : ("Joao", 3)

println!("{:?}", game.delete());
// output : "game deleted: id -> 0"

// game.read_winner();
// this will give error
// because the game was dropped, no longer exists on the heap
// This will give an error as the game was dropped with `delete` and no longer exists
}
```

And its output:

```console
$ cargo run
("Same score! tied", 0)
("Same score! tied", 2)
("Joao", 3)
None
None
Some(("Joao", 3))
"game deleted: id -> 0"
$
```
Expand Down
14 changes: 6 additions & 8 deletions subjects/bowling_score/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,19 @@ pub enum Error {
GameComplete,
}

pub struct BowlingGame {
...
}
pub struct BowlingGame {}

impl BowlingGame {
pub fn new() -> Self {
unimplemented!();
todo!();
}

pub fn roll(&mut self, pins: u16) -> Result<(), Error> {
unimplemented!();
pub fn roll(&mut self, pins: u32) -> Result<(), Error> {
todo!();
}

pub fn score(&mut self) -> Some(u16) {
unimplemented!();
pub fn score(&self) -> Option<u32> {
todo!();
}
}
```
Expand Down
39 changes: 21 additions & 18 deletions subjects/box_it/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,19 @@

Create the following **functions**:

- `transform_and_save_on_heap`: which accepts a string of numbers separated by spaces. If a number has a `'k'` as a suffix it should be multiplied by 1000. The function transforms those numbers into a vector of `u32`, and saves them in the heap using `Box`.
- `parse_into_boxed`: which accepts a string of numbers separated by spaces. If a number has a `k` as a suffix it should be multiplied by 1000. The function parses these numbers and boxes them into a vector of `Box<u32>`.

- `take_value_ownership`: which accepts the return value from `transform_and_save_on_heap`, unboxes the value, and returns it.
- `into_unboxed`: which accepts the value returned from `parse_into_boxed` and unboxes each element into another vector.

### Expected Functions

```rust
pub fn transform_and_save_on_heap(s: String) -> Box<Vec<u32>> {

pub fn parse_into_boxed(s: String) -> Vec<Box<u32>> {
todo!()
}
pub fn take_value_ownership(a: Box<Vec<u32>>) -> Vec<u32> {

pub fn into_unboxed(a: Vec<Box<u32>>) -> Vec<u32> {
todo!()
}
```

Expand All @@ -24,31 +25,33 @@ pub fn take_value_ownership(a: Box<Vec<u32>>) -> Vec<u32> {
Here is a program to test your functions

```rust
use std::mem;

use box_it::*;

fn main() {
let new_str = String::from("5.5k 8.9k 32");
let s = "5.5k 8.9k 32".to_owned();

let boxed = parse_into_boxed(s);
println!("Element value: {:?}", boxed[0]);
println!("Element size: {:?} bytes", mem::size_of_val(&boxed[0]));

// creating a variable and we save it in the Heap
let a_h = transform_and_save_on_heap(new_str);
println!("Box value : {:?}", &a_h);
println!("size occupied in the stack : {:?} bytes", (std::mem::size_of_val(&a_h)));
let unboxed = into_unboxed(boxed);
println!("Element value: {:?}", unboxed[0]);
println!("Element size: {:?} bytes", mem::size_of_val(&unboxed[0]));

let a_b_v = take_value_ownership(a_h);
println!("value : {:?}", &a_b_v);
println!("size occupied in the stack : {:?} bytes", (std::mem::size_of_val(&a_b_v)));
// whenever the box, in this case "a_h", goes out of scope it will be deallocated, freed
// As with everything related to regular Rust memory management, both the `Vec` and the `Box`es will be properly dropped when out of scope and freed, ensuring no leaks
}
```

And its output:

```console
$ cargo run
Box value : [5500, 8900, 32]
size occupied in the stack : 8 bytes
value : [5500, 8900, 32]
size occupied in the stack : 24 bytes
Element value: 5500
Element size: 8 bytes
Element value: 5500
Element size: 4 bytes
$
```

Expand Down
63 changes: 45 additions & 18 deletions subjects/box_recursion/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,32 @@
Using the given code, create the following **associated functions**:

- `new`: which will initialize the `WorkEnvironment` with `grade` set to `None`.
- `add_worker`: which receives two strings, one being the role and the other the name of the worker. It will add the worker at the start of the list.
- `remove_worker`: which removes the last worker that was placed in the `WorkEnvironment`, this function returns an `Option` with the name of the worker.
- `add_worker`: which receives a name of a worker and a role. It will add the worker at the start of the list.
- `remove_worker`: which removes the last worker that was placed in the `WorkEnvironment`, this function returns an `Option` with the name of the removed worker.
- `last_worker`: which returns an `Option` with a tuple containing the name and role of the last added worker.

You must also create a type named `Link`. This will be the connection between the `WorkEnvironment` and `Worker` structures. This will be a recursion type, and it must point to `None` if there is no `Worker` to point to.
You must also create a `Role` enum which can be `CEO`, `Manager`, or `Worker`, and will represent the role of a worker. This enum should implement the `From` trait for `&str`.

Additionally, create a type named `Link`, which will be the connection between the `WorkEnvironment` and `Worker` structures. It will point to `None` if there is no `Worker` to point to.

### Expected Functions and structures

```rust
#[derive(Debug, PartialEq)]
pub enum Role {
CEO,
Manager,
Worker,
}

impl From<&str> for Role {}

#[derive(Debug)]
pub struct WorkEnvironment {
pub grade: Link,
}

pub type Link =
pub type Link;

#[derive(Debug)]
pub struct Worker {
Expand All @@ -29,10 +40,21 @@ pub struct Worker {
}

impl WorkEnvironment {
pub fn new() -> WorkEnvironment {}
pub fn add_worker(&mut self, role: String, name: String) {}
pub fn remove_worker(&mut self) -> Option<String> {}
pub fn last_worker(&self) -> Option<(String, String)> {}
pub fn new() -> Self {
todo!()
}

pub fn add_worker(&mut self, name: &str, role: &str) {
todo!()
}

pub fn remove_worker(&mut self) -> Option<String> {
todo!()
}

pub fn last_worker(&self) -> Option<(String, Role)> {
todo!()
}
}
```

Expand All @@ -45,19 +67,24 @@ use box_recursion::*;

fn main() {
let mut list = WorkEnvironment::new();
list.add_worker(String::from("CEO"), String::from("Marie"));
list.add_worker(String::from("Manager"), String::from("Monica"));
list.add_worker(String::from("Normal Worker"), String::from("Ana"));
list.add_worker(String::from("Normal Worker"), String::from("Alice"));

list.add_worker("Marie", "CEO");
list.add_worker("Monica", "Manager");
list.add_worker("Ana", "Normal Worker");
list.add_worker("Alice", "Normal Worker");

println!("{:#?}", list);

println!("{:?}", list.last_worker());

list.remove_worker();
list.remove_worker();
list.remove_worker();

println!("{:?}", list);

list.remove_worker();

println!("{:?}", list);
}
```
Expand All @@ -69,19 +96,19 @@ $ cargo run
WorkEnvironment {
grade: Some(
Worker {
role: "Normal Worker",
role: Worker,
name: "Alice",
next: Some(
Worker {
role: "Normal Worker",
role: Worker,
name: "Ana",
next: Some(
Worker {
role: "Manager",
role: Manager,
name: "Monica",
next: Some(
Worker {
role: "CEO",
role: CEO,
name: "Marie",
next: None,
},
Expand All @@ -93,8 +120,8 @@ WorkEnvironment {
},
),
}
Some(("Alice", "Normal Worker"))
WorkEnvironment { grade: Some(Worker { role: "CEO", name: "Marie", next: None }) }
Some(("Alice", Worker))
WorkEnvironment { grade: Some(Worker { role: CEO, name: "Marie", next: None }) }
WorkEnvironment { grade: None }
$
```
Expand Down
Loading
Loading