Skip to content

Commit 7abfbd2

Browse files
author
fmoko
authored
Merge pull request #572 from sazid/main
2 parents f38f42f + 633c00c commit 7abfbd2

File tree

6 files changed

+264
-0
lines changed

6 files changed

+264
-0
lines changed

exercises/collections/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
### Collections
2+
3+
Rust’s standard library includes a number of very useful data
4+
structures called collections. Most other data types represent one
5+
specific value, but collections can contain multiple values. Unlike
6+
the built-in array and tuple types, the data these collections point
7+
to is stored on the heap, which means the amount of data does not need
8+
to be known at compile time and can grow or shrink as the program
9+
runs.
10+
11+
This exercise will get you familiar with two fundamental data
12+
structures that are used very often in Rust programs:
13+
14+
* A *vector* allows you to store a variable number of values next to
15+
each other.
16+
* A *hash map* allows you to associate a value with a particular key.
17+
You may also know this by the names *map* in C++, *dictionary* in
18+
Python or an *associative array* in other languages.
19+
20+
[Rust book chapter](https://doc.rust-lang.org/stable/book/ch08-01-vectors.html)

exercises/collections/hashmap1.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// hashmap1.rs
2+
// A basket of fruits in the form of a hash map needs to be defined.
3+
// The key represents the name of the fruit and the value represents
4+
// how many of that particular fruit is in the basket. You have to put
5+
// at least three different types of fruits (e.g apple, banana, mango)
6+
// in the basket and the total count of all the fruits should be at
7+
// least five.
8+
//
9+
// Make me compile and pass the tests!
10+
//
11+
// Execute the command `rustlings hint collections3` if you need
12+
// hints.
13+
14+
// I AM NOT DONE
15+
16+
use std::collections::HashMap;
17+
18+
fn fruit_basket() -> HashMap<String, u32> {
19+
let mut basket = // TODO: declare your hash map here.
20+
21+
// Two bananas are already given for you :)
22+
basket.insert(String::from("banana"), 2);
23+
24+
// TODO: Put more fruits in your basket here.
25+
26+
basket
27+
}
28+
29+
#[cfg(test)]
30+
mod tests {
31+
use super::*;
32+
33+
#[test]
34+
fn at_least_three_types_of_fruits() {
35+
let basket = fruit_basket();
36+
assert!(basket.len() >= 3);
37+
}
38+
39+
#[test]
40+
fn at_least_five_fruits() {
41+
let basket = fruit_basket();
42+
assert!(basket
43+
.values()
44+
.sum::<u32>() >= 5);
45+
}
46+
}

exercises/collections/hashmap2.rs

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// hashmap2.rs
2+
3+
// A basket of fruits in the form of a hash map is given. The key
4+
// represents the name of the fruit and the value represents how many
5+
// of that particular fruit is in the basket. You have to put *MORE
6+
// THAN 11* fruits in the basket. Three types of fruits - Apple (4),
7+
// Mango (2) and Lichi (5) are already given in the basket. You are
8+
// not allowed to insert any more of these fruits!
9+
//
10+
// Make me pass the tests!
11+
//
12+
// Execute the command `rustlings hint collections4` if you need
13+
// hints.
14+
15+
// I AM NOT DONE
16+
17+
use std::collections::HashMap;
18+
19+
#[derive(Hash, PartialEq, Eq)]
20+
enum Fruit {
21+
Apple,
22+
Banana,
23+
Mango,
24+
Lichi,
25+
Pineapple,
26+
}
27+
28+
fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
29+
let fruit_kinds = vec![
30+
Fruit::Apple,
31+
Fruit::Banana,
32+
Fruit::Mango,
33+
Fruit::Lichi,
34+
Fruit::Pineapple,
35+
];
36+
37+
for fruit in fruit_kinds {
38+
// TODO: Put new fruits if not already present. Note that you
39+
// are not allowed to put any type of fruit that's already
40+
// present!
41+
}
42+
}
43+
44+
#[cfg(test)]
45+
mod tests {
46+
use super::*;
47+
48+
fn get_fruit_basket() -> HashMap<Fruit, u32> {
49+
let mut basket = HashMap::<Fruit, u32>::new();
50+
basket.insert(Fruit::Apple, 4);
51+
basket.insert(Fruit::Mango, 2);
52+
basket.insert(Fruit::Lichi, 5);
53+
54+
basket
55+
}
56+
57+
#[test]
58+
fn test_given_fruits_are_not_modified() {
59+
let mut basket = get_fruit_basket();
60+
fruit_basket(&mut basket);
61+
assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4);
62+
assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2);
63+
assert_eq!(*basket.get(&Fruit::Lichi).unwrap(), 5);
64+
}
65+
66+
#[test]
67+
fn at_least_five_types_of_fruits() {
68+
let mut basket = get_fruit_basket();
69+
fruit_basket(&mut basket);
70+
let count_fruit_kinds = basket.len();
71+
assert!(count_fruit_kinds == 5);
72+
}
73+
74+
#[test]
75+
fn greater_than_eleven_fruits() {
76+
let mut basket = get_fruit_basket();
77+
fruit_basket(&mut basket);
78+
let count = basket
79+
.values()
80+
.sum::<u32>();
81+
assert!(count > 11);
82+
}
83+
}

exercises/collections/vec1.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// vec1.rs
2+
// Your task is to create a `Vec` which holds the exact same elements
3+
// as in the array `a`.
4+
// Make me compile and pass the test!
5+
// Execute the command `rustlings hint collections1` if you need hints.
6+
7+
// I AM NOT DONE
8+
9+
fn array_and_vec() -> ([i32; 4], Vec<i32>) {
10+
let a = [10, 20, 30, 40]; // a plain array
11+
let v = // TODO: declare your vector here with the macro for vectors
12+
13+
(a, v)
14+
}
15+
16+
#[cfg(test)]
17+
mod tests {
18+
use super::*;
19+
20+
#[test]
21+
fn test_array_and_vec_similarity() {
22+
let (a, v) = array_and_vec();
23+
assert!(a.iter().zip(v.iter()).all(|(x, y)| x == y));
24+
}
25+
}

exercises/collections/vec2.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// vec2.rs
2+
// A Vec of even numbers is given. Your task is to complete the loop
3+
// so that each number in the Vec is multiplied by 2.
4+
//
5+
// Make me pass the test!
6+
//
7+
// Execute the command `rustlings hint collections2` if you need
8+
// hints.
9+
10+
// I AM NOT DONE
11+
12+
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
13+
for i in v.iter_mut() {
14+
// TODO: Fill this up so that each element in the Vec `v` is
15+
// multiplied by 2.
16+
}
17+
18+
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
19+
v
20+
}
21+
22+
#[cfg(test)]
23+
mod tests {
24+
use super::*;
25+
26+
#[test]
27+
fn test_vec_loop() {
28+
let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();
29+
let ans = vec_loop(v.clone());
30+
31+
assert_eq!(
32+
ans,
33+
v.iter()
34+
.map(|x| x * 2)
35+
.collect::<Vec<i32>>()
36+
);
37+
}
38+
}

info.toml

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,58 @@ its internal structure (the `fruits` and `veggies` modules and
370370
associated constants). It's almost there except for one keyword missing for
371371
each constant."""
372372

373+
# COLLECTIONS
374+
375+
[[exercises]]
376+
name = "collections1"
377+
path = "exercises/collections/vec1.rs"
378+
mode = "test"
379+
hint = """
380+
In Rust, there are two ways to define a Vector.
381+
382+
1. One way is to use the `Vec::new()` function to create a new vector
383+
and fill it with the `push()` method.
384+
385+
2. The second way, which is simpler is to use the `vec![]` macro and
386+
define your elements inside the square brackets.
387+
388+
Check this chapter: https://doc.rust-lang.org/stable/book/ch08-01-vectors.html
389+
of the Rust book to learn more.
390+
"""
391+
392+
[[exercises]]
393+
name = "collections2"
394+
path = "exercises/collections/vec2.rs"
395+
mode = "test"
396+
hint = """
397+
Hint 1: `i` is each element from the Vec as they are being iterated.
398+
Can you try multiplying this?
399+
400+
Hint 2: Check the suggestion from the compiler error ;)
401+
"""
402+
403+
[[exercises]]
404+
name = "collections3"
405+
path = "exercises/collections/hashmap1.rs"
406+
mode = "test"
407+
hint = """
408+
Hint 1: Take a look at the return type of the function to figure out
409+
the type for the `basket`.
410+
411+
Hint 2: Number of fruits should be at least 5. And you have to put
412+
at least three different types of fruits.
413+
"""
414+
415+
[[exercises]]
416+
name = "collections4"
417+
path = "exercises/collections/hashmap2.rs"
418+
mode = "test"
419+
hint = """
420+
Use the `entry()` and `or_insert()` methods of `HashMap` to achieve this.
421+
422+
Learn more at https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#only-inserting-a-value-if-the-key-has-no-value
423+
"""
424+
373425
# MACROS
374426

375427
[[exercises]]

0 commit comments

Comments
 (0)