rustlings/exercises/vecs/vecs2.rs

44 lines
1013 B
Rust
Raw Normal View History

// vecs2.rs
2020-10-26 00:54:32 -06: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.
//
// Make me pass the test!
//
// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint.
2020-10-26 00:54:32 -06:00
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for i in v.iter_mut() {
2023-02-17 12:44:18 -06:00
*i *= 2
2020-10-26 00:54:32 -06:00
}
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
v
}
2022-07-12 08:05:47 -05:00
fn vec_map(v: &Vec<i32>) -> Vec<i32> {
v.iter().map(|num| {
2023-02-17 12:44:18 -06:00
num * 2
2022-07-12 08:05:47 -05:00
}).collect()
}
2020-10-26 00:54:32 -06: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());
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());
2020-10-26 00:54:32 -06:00
}
2022-07-12 08:05:47 -05: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 00:54:32 -06:00
}