2022-07-12 13:16:25 +00:00
|
|
|
// vecs2.rs
|
2023-05-29 17:39:08 +00:00
|
|
|
//
|
|
|
|
// A Vec of even numbers is given. Your task is to complete the loop so that
|
|
|
|
// each number in the Vec is multiplied by 2.
|
2020-10-26 06:54:32 +00:00
|
|
|
//
|
|
|
|
// Make me pass the test!
|
|
|
|
//
|
2022-07-12 13:16:25 +00:00
|
|
|
// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint.
|
2020-10-26 06:54:32 +00:00
|
|
|
|
|
|
|
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
|
2023-03-10 19:13:06 +00:00
|
|
|
for element in v.iter_mut() {
|
2020-10-26 06:54:32 +00:00
|
|
|
// TODO: Fill this up so that each element in the Vec `v` is
|
|
|
|
// multiplied by 2.
|
2024-01-20 06:47:05 +00:00
|
|
|
*element *= 2;
|
2020-10-26 06:54:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
|
|
|
|
v
|
|
|
|
}
|
|
|
|
|
2022-07-12 13:05:47 +00:00
|
|
|
fn vec_map(v: &Vec<i32>) -> Vec<i32> {
|
2023-03-10 19:13:06 +00:00
|
|
|
v.iter().map(|element| {
|
2022-07-12 13:05:47 +00:00
|
|
|
// TODO: Do the same thing as above - but instead of mutating the
|
|
|
|
// Vec, you can just return the new number!
|
2024-01-20 06:47:05 +00:00
|
|
|
element * 2
|
2022-07-12 13:05:47 +00:00
|
|
|
}).collect()
|
|
|
|
}
|
|
|
|
|
2020-10-26 06:54:32 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_vec_loop() {
|
|
|
|
let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();
|
|
|
|
let ans = vec_loop(v.clone());
|
|
|
|
|
2021-03-18 17:39:22 +00:00
|
|
|
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());
|
2020-10-26 06:54:32 +00:00
|
|
|
}
|
2022-07-12 13:05:47 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_vec_map() {
|
|
|
|
let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();
|
|
|
|
let ans = vec_map(&v);
|
|
|
|
|
|
|
|
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());
|
|
|
|
}
|
2020-10-26 06:54:32 +00:00
|
|
|
}
|