rustlings

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

vecs2.rs (1456B)


      1 fn vec_loop(input: &[i32]) -> Vec<i32> {
      2     let mut output = Vec::new();
      3 
      4     for element in input {
      5         output.push(2 * element);
      6     }
      7 
      8     output
      9 }
     10 
     11 fn vec_map_example(input: &[i32]) -> Vec<i32> {
     12     // An example of collecting a vector after mapping.
     13     // We map each element of the `input` slice to its value plus 1.
     14     // If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`.
     15     input.iter().map(|element| element + 1).collect()
     16 }
     17 
     18 fn vec_map(input: &[i32]) -> Vec<i32> {
     19     // We will dive deeper into iterators, but for now, this is all what you
     20     // had to do!
     21     // Advanced note: This method is more efficient because it automatically
     22     // preallocates enough capacity. This can be done manually in `vec_loop`
     23     // using `Vec::with_capacity(input.len())` instead of `Vec::new()`.
     24     input.iter().map(|element| 2 * element).collect()
     25 }
     26 
     27 fn main() {
     28     // You can optionally experiment here.
     29 }
     30 
     31 #[cfg(test)]
     32 mod tests {
     33     use super::*;
     34 
     35     #[test]
     36     fn test_vec_loop() {
     37         let input = [2, 4, 6, 8, 10];
     38         let ans = vec_loop(&input);
     39         assert_eq!(ans, [4, 8, 12, 16, 20]);
     40     }
     41 
     42     #[test]
     43     fn test_vec_map_example() {
     44         let input = [1, 2, 3];
     45         let ans = vec_map_example(&input);
     46         assert_eq!(ans, [2, 3, 4]);
     47     }
     48 
     49     #[test]
     50     fn test_vec_map() {
     51         let input = [2, 4, 6, 8, 10];
     52         let ans = vec_map(&input);
     53         assert_eq!(ans, [4, 8, 12, 16, 20]);
     54     }
     55 }