diff options
| author | mo8it <mo8it@proton.me> | 2024-06-21 14:52:11 +0200 |
|---|---|---|
| committer | mo8it <mo8it@proton.me> | 2024-06-21 14:52:11 +0200 |
| commit | 835ec7262247a341295c1d6f3772901a5fad5148 (patch) | |
| tree | e8d19e0c5c64cf724c807903e1bfdd6f6d782f39 /solutions/05_vecs | |
| parent | a9f0c7bf1f00ab19733953d3121d462eede34466 (diff) | |
vecs2 solution + significant change to have a better comparison between both methods
Diffstat (limited to 'solutions/05_vecs')
| -rw-r--r-- | solutions/05_vecs/vecs2.rs | 51 |
1 files changed, 50 insertions, 1 deletions
diff --git a/solutions/05_vecs/vecs2.rs b/solutions/05_vecs/vecs2.rs index 4e18198..32c1c0f 100644 --- a/solutions/05_vecs/vecs2.rs +++ b/solutions/05_vecs/vecs2.rs @@ -1 +1,50 @@ -// Solutions will be available before the stable release. Thank you for testing the beta version 🥰 +fn vec_loop(input: &[i32]) -> Vec<i32> { + let mut output = Vec::new(); + + for element in input { + output.push(2 * element); + } + + output +} + +fn vec_map_example(input: &[i32]) -> Vec<i32> { + // An example of collecting a vector after mapping. + // We map each element of the `input` slice to its value plus 1. + // If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`. + input.iter().map(|element| element + 1).collect() +} + +fn vec_map(input: &[i32]) -> Vec<i32> { + input.iter().map(|element| 2 * element).collect() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_vec_loop() { + let input = [2, 4, 6, 8, 10]; + let ans = vec_loop(&input); + assert_eq!(ans, [4, 8, 12, 16, 20]); + } + + #[test] + fn test_vec_map_example() { + let input = [1, 2, 3]; + let ans = vec_map_example(&input); + assert_eq!(ans, [2, 3, 4]); + } + + #[test] + fn test_vec_map() { + let input = [2, 4, 6, 8, 10]; + let ans = vec_map(&input); + assert_eq!(ans, [4, 8, 12, 16, 20]); + } +} |
