Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How I get the real median (5.5) from this?

The result of this code is 6 but the correct answer is 5.5

I’m trying to get the median of the vector of numbers from 1 to 10.

fn vector_median(vector: &mut Vec<i32>) -> f64 {
    vector.sort();
    if (vector.len()) % 2 == 0 {
        let numbers = (vector[vector.len() / 2], vector[(vector.len() / 2) - 1]);
        (f64::from(numbers.0) + f64::from(numbers.1)) / 2.0
        
    } else {
        return f64::from(vector[vector.len() / 2]);
    }
}

fn main() {
    let mut vector1 = vec![1, 5, 6, 3, 2, 7, 9, 8, 4, 10];
    let median = vector_median(&mut vector1);

    println!("{:?}", vector1);

    println!("La media es {median}");
}

I’m hoping for a result a float number f64, specifically 5.5 with that vector.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The even/odd check is backwards.

  • If there’s an odd number of elements then you can simply return the middle one.

    [1, 2, 3]
        ^
    
  • If there’s an even number then you want to average the two closest to the middle.

    [1, 2, 3, 4]
        ^^^^
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading