How do I repeat some elements in a vector based on a condition?

Viewed 1538

I encountered this problem during a kata. My more readable implementation was the following:

use std::vec::Vec;

fn repeat_even(v: Vec<i32>) -> Vec<i32> {
    v.into_iter().flat_map(|x| match x % 2 { 0 => vec![x, x], _ => vec![x] }).collect()
}

fn main() {
    let v = vec![1, 2, 3, 4, 6];
    assert_eq!(repeat_even(v), vec![1, 2, 2, 3, 4, 4, 6, 6]);
}

I have two questions about it:

  • Is it necessary to create another Vec? Is is possible to use the same Vec, i.e. modify it while iterating?

  • My solution is, I imagine, inefficient: I allocate a lot of vectors, and I have no guarantee that this will be optimized. Is there a better solution: readable and with less allocation?

4 Answers
Related