rustlings

solving rustlings ft. dracuxan
git clone [email protected]:dracuxan/rustlings.git
Log | Files | Refs

vecs2.rs (1494B)


      1 fn vec_loop(input: &[i32; 5]) -> Vec<i32> {
      2     let mut output = Vec::new();
      3 
      4     for element in input {
      5         // TODO: Multiply each element in the `input` slice by 2 and push it to
      6         // the `output` vector.
      7         output.push(element * 2);
      8     }
      9 
     10     output
     11 }
     12 
     13 fn vec_map_example(input: &[i32; 3]) -> Vec<i32> {
     14     // An example of collecting a vector after mapping.
     15     // We map each element of the `input` slice to its value plus 1.
     16     // If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`.
     17     input.iter().map(|element| element + 1).collect()
     18 }
     19 
     20 fn vec_map(input: &[i32; 5]) -> Vec<i32> {
     21     // TODO: Here, we also want to multiply each element in the `input` slice
     22     // by 2, but with iterator mapping instead of manually pushing into an empty
     23     // vector.
     24     // See the example in the function `vec_map_example` above.
     25     input.iter().map(|element| element * 2).collect()
     26 }
     27 
     28 fn main() {
     29     // You can optionally experiment here.
     30 }
     31 
     32 #[cfg(test)]
     33 mod tests {
     34     use super::*;
     35 
     36     #[test]
     37     fn test_vec_loop() {
     38         let input = [2, 4, 6, 8, 10];
     39         let ans = vec_loop(&input);
     40         assert_eq!(ans, [4, 8, 12, 16, 20]);
     41     }
     42 
     43     #[test]
     44     fn test_vec_map_example() {
     45         let input = [1, 2, 3];
     46         let ans = vec_map_example(&input);
     47         assert_eq!(ans, [2, 3, 4]);
     48     }
     49 
     50     #[test]
     51     fn test_vec_map() {
     52         let input = [2, 4, 6, 8, 10];
     53         let ans = vec_map(&input);
     54         assert_eq!(ans, [4, 8, 12, 16, 20]);
     55     }
     56 }