3

Hi I wrote a function that maps a vector to the interval [0,1]:

fn vec2interval(v: &Vec<f32>) -> Vec<f32> {
    let total: f32 = v.iter().sum();
    let mut interval: Vec<f32> = vec![0f32; v.len()];
    interval[0] = v[0] / total;
    for i in 1..v.len() {
        interval[i] = interval[i-1] + v[i] / total;
    }
    return interval;
}

Is there any way to do the same with iterator? I wrote the following but it's slower and needs a for loop:

fn vec2interval(v: &Vec<f32>) -> Vec<f32> {
    let total: f32 = v.iter().sum();
    let mut interval: Vec<f32> = v
        .iter()
        .map(|x| x / total)
        .collect::<Vec<f32>>();
    for i in 1..v.len() {
        interval[i] = interval[i-1] + interval[i];
    }
    return interval;
}
MindSwipe
  • 7,193
  • 24
  • 47
Jihyun
  • 883
  • 5
  • 17
  • See [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/3650362) – trent Jul 09 '20 at 10:38

1 Answers1

3

scan can do all of the job:

fn vec2interval(v: &Vec<f32>) -> Vec<f32> {
    let total: f32 = v.iter().sum();

    v.iter()
        .scan(0.0, |acc, x| {
            *acc += x / total;
            Some(*acc)
        })
        .collect()
}

Also, slice (&[u8]) better be used instead of Vec<_> as a parameter.

Kitsu
  • 3,166
  • 14
  • 28
  • Probably simpler to remove the `map` and do the division inside the `scan`… – Jmb Jul 09 '20 at 06:41
  • thank you! The code worked perfect! It is a little slower than a simple for-loop but is cool and hope it's faster for a larger input? – Jihyun Jul 17 '20 at 03:55
  • Iterators sometimes can be [better](https://stackoverflow.com/questions/54490896/why-is-my-for-loop-code-slower-than-an-iterator) in performance and other time [may suck](https://github.com/rust-lang/rust/issues/57517). Without a proper benchmarking it's hard to reason about it, take a look at [quickcheck](https://crates.io/crates/quickcheck) if you'd like to. Also consider [this](https://stackoverflow.com/questions/55675093/what-are-the-performance-impacts-of-functional-rust/55676567#55676567) explanation. – Kitsu Jul 17 '20 at 05:42