mirror of
https://github.com/notohh/rustlings.git
synced 2024-12-23 03:38:09 -05:00
48 lines
1.2 KiB
Rust
48 lines
1.2 KiB
Rust
// 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!
|
|
|
|
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
|
|
for element in v.iter_mut() {
|
|
// TODO: Fill this up so that each element in the Vec `v` is
|
|
// multiplied by 2.
|
|
???
|
|
}
|
|
|
|
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
|
|
v
|
|
}
|
|
|
|
fn vec_map(v: &Vec<i32>) -> Vec<i32> {
|
|
v.iter().map(|element| {
|
|
// TODO: Do the same thing as above - but instead of mutating the
|
|
// Vec, you can just return the new number!
|
|
???
|
|
}).collect()
|
|
}
|
|
|
|
fn main() {
|
|
// You can optionally experiment here.
|
|
}
|
|
|
|
#[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>>());
|
|
}
|
|
|
|
#[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>>());
|
|
}
|
|
}
|