Add collections solutions

This commit is contained in:
David Bailey 2021-01-16 20:41:53 +00:00
parent 6e353820be
commit c1de217d0e
4 changed files with 9 additions and 28 deletions

View file

@ -11,17 +11,16 @@
// Execute the command `rustlings hint collections3` if you need
// hints.
// I AM NOT DONE
use std::collections::HashMap;
fn fruit_basket() -> HashMap<String, u32> {
let mut basket = // TODO: declare your hash map here.
let mut basket = HashMap::new();
// Two bananas are already given for you :)
basket.insert(String::from("banana"), 2);
// TODO: Put more fruits in your basket here.
basket.insert(String::from("orange"), 3);
basket.insert(String::from("strawberry"), 5);
basket
}
@ -39,8 +38,6 @@ mod tests {
#[test]
fn at_least_five_fruits() {
let basket = fruit_basket();
assert!(basket
.values()
.sum::<u32>() >= 5);
assert!(basket.values().sum::<u32>() >= 5);
}
}

View file

@ -12,8 +12,6 @@
// Execute the command `rustlings hint collections4` if you need
// hints.
// I AM NOT DONE
use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq)]
@ -35,9 +33,7 @@ fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
];
for fruit in fruit_kinds {
// TODO: Put new fruits if not already present. Note that you
// are not allowed to put any type of fruit that's already
// present!
basket.entry(fruit).or_insert(1);
}
}
@ -75,9 +71,7 @@ mod tests {
fn greater_than_eleven_fruits() {
let mut basket = get_fruit_basket();
fruit_basket(&mut basket);
let count = basket
.values()
.sum::<u32>();
let count = basket.values().sum::<u32>();
assert!(count > 11);
}
}

View file

@ -4,11 +4,9 @@
// Make me compile and pass the test!
// Execute the command `rustlings hint collections1` if you need hints.
// I AM NOT DONE
fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // a plain array
let v = // TODO: declare your vector here with the macro for vectors
let v = vec![10, 20, 30, 40];
(a, v)
}

View file

@ -7,12 +7,9 @@
// Execute the command `rustlings hint collections2` if you need
// hints.
// I AM NOT DONE
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for i in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
*i *= 2;
}
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
@ -28,11 +25,6 @@ mod tests {
let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();
let ans = vec_loop(v.clone());
assert_eq!(
ans,
v.iter()
.map(|x| x * 2)
.collect::<Vec<i32>>()
);
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());
}
}