A very very strange bug

fn main() {
    let len = 10000;
    let mut vs = vec![1; len];
    let mut sum = 0;
    for i in &vs {
        sum = sum + i;
    }
    dbg!(sum);
    let mut x = rand::thread_rng();
    for _ in 0..len * 100 {
        let p = x.gen_range(0..len);
        let q = x.gen_range(0..len);

        vs[q] = vs[p] + vs[q];
        vs[p] = 0;
    }
    let mut sum = 0;
    for i in &vs {
        sum = sum + i;
    }
    dbg!(sum);
}

Something like this would be the output

[src/main.rs:15] sum= 10000
[src/main.rs:29] sum= 9709

I don't understand why the value of sum would be less than 10000 after the code has been executed.
The only place where vs is being changed is

        vs[q] = vs[p] + vs[q];
        vs[p] = 0;

but I am increasing value of one entry by the same amount I am decreasing value of another entry.
How can sum of the elements in the vector change?

p and q can be identical. If you wrap your mutation in a if p != q, your sum will stay 10_000.

7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.