Search code examples
rustvector

How to construct a vector based on a repeating sequence?


I am writing a sieve of Eratosthenes, for this you want to start a vector of booleans with odd indices true and even indices false. Currently my code for getting that is:

let mut is_prime: Vec<bool> = vec![true; capacity];
is_prime.iter_mut().step_by(2).for_each(|m| *m = false);

However that doesn't work to create an alternating true false sequence. How can I achieve this?

Note: I know this won't have a massive impact on performance in this case, I but I thought it was an interesting problem and suspect there may be cases where it would make a difference.


Solution

  • You can combine a few iterator utilities to do this efficiently and ergonomically:

    let mut is_prime: Vec<_> = std::iter::repeat([true, false])
        .flatten()
        .take(capacity)
        .collect();
    

    Note the iterator exactly knows its length, which allows collect to build a vector with enough capacity allocated in advance.