从一系列频率中获取中值? [英] Getting median from an array of frequencies?

查看:80
本文介绍了从一系列频率中获取中值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,例如,在 array [1] 中将包含很多次出现在数字列表中,但是同样会包含 array [2] 有很多人.

I have an array which for example in array[1] will contain however many times one occurred in a list of numbers, likewise array[2] will be however many twos there were.

这是我到目前为止尝试过的

This is what I have tried so far

    int tot = 0;
    for(int i=0; i<array.length; i++){
        tot += array[i];
    }
    int mid = tot/2;
    int med = array[mid];
    return med; 

这行不通,我觉得还有很多我没有做的计算.任何指导表示赞赏.谢谢!

This doesn't work, and I feel like there's a lot more calculations that I haven't done. Any guidance is appreciated. Thanks!

推荐答案

这里的问题是您需要在看到中间"的位置找到索引:

The problem here is that you need to find the index where you have seen the "middle":

int tot = 0;
for(int i=0; i<array.length; i++){
    tot += array[i];
}
int mid = tot/2;
int med = 0;
tot = 0;
for(int i=0; i<array.length; i++){
    tot += array[i];
    if(tot >= mid) { 
        med = i; 
        break; 
    }
}

return med;

更新:正如Ajay Reddy在评论中指出的那样,以上代码仅适用于数组长度不均匀的情况.对于偶数长度,有一个上下中位数,它们的平均值就是实际中位数.如果您确实希望这取决于您随后对中位数的处理方式(如果确实需要使用上述代码,则会找到较低的中位数).

Update: As Ajay Reddy stated in the comments, above code is only correct for an uneven length of the array. For even length, there is an upper and lower median, the average of which is the actual median. If you actually want that depends on what you are doing afterwards with the median (if it needs to actually occur use above code, it finds the lower median).

int tot = 0;
for(int i=0; i<array.length; i++){
    tot += array[i];
}
float mid = tot/2;
int upper_med = 0;
int lower_med = 0;
tot = 0;
for(int i=0; i<array.length; i++){
    tot += array[i];
    if(i > 0 && array[i-1] > 0) {
        lower_med = i;
    }
    if(tot >= mid) { 
        upper_med = i; 
        break; 
    }
}

return array.length % 2 == 0 ? (float)(upper_med + lower_med)/2 : lower_med; // cast to float or not according to your requirements

这篇关于从一系列频率中获取中值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆