2

我想创建一个程序来帮助我进行统计,但是我从一开始就遇到了问题,而且我在计算具有随机数且只有一维的数组的相对频率时遇到了很大的麻烦。

例如生成这些数字:

{3, 5, 5, 2, 4, 1, 3, 5, 4}

我希望程序告诉我3重复 2 次、43 次和55 次

我创建了一个类来对这些值进行排序以计算中位数,第一和第三四分位数,但我仍然不知道如何找到频率以计算其他值

谢谢你的时间

PS:不知道这是否会影响任何东西,但我正在使用netbeans

4

4 回答 4

3

你肯定在寻找这个:收藏:频率

如果您没有集合,请先将数组转换为列表:

Collections.frequency(Arrays.asList(yourArray), new Integer(3))
于 2013-01-10T20:51:30.077 回答
2

如果您的数字范围相对较小,则可能首选使用计数器数组。例如,如果您的随机数在区间内,[1,5]那么您可以使用大小为 5 的数组来存储和更新频率计数器:

int[] numbers = {3, 5, 5, 2, 4, 1, 3, 5, 4} ;
int[] frequencies = new int[5];

for(int n : numbers)
    frequencies[n-1]++;

输出数组frequencies):

1 1 2 2 3

编辑:

此方法可应用于所有范围。例如,假设您有范围内的数字[500,505]

int[] frequencies = new int[6];

for(int n : numbers)
    frequencies[n-500]++;
于 2013-01-10T20:55:49.077 回答
0
    int[] numbers = {100, 101, 102, 103, 5 , 4, 4 , 6} ;

    Map<Integer, Integer> m = new HashMap<Integer, Integer>();
    for(int num: numbers){
        if(m.containsKey(num)){
            m.put(num, m.get(num)+1);
        }else{
            m.put(num, 1);
        }   
    }
    for (Map.Entry<Integer, Integer> entry : m.entrySet()) {
        System.out.println("Key: " + entry.getKey() + " | Frequencey: " + entry.getValue());
    }
于 2013-01-11T02:14:44.773 回答
0

编辑:您可以使用地图来存储频率,如下所示:

import java.util.HashMap;
import java.util.Map;

public class Frequency {
    public static void main(String[] args) {
        int[] nums = { 3, 5, 5, 2, 4, 1, 3, 5, 4 };
        int count = 1;
        // number,frequency type map.
        Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != -1) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[j] != -1) {
                        if (nums[i] == nums[j]) {
                            // -1 is an indicator that this number is already counted.
                            // You should replace it such a number which is sure to be not coming in array.
                            nums[j] = -1;
                            count++;
                        }
                    }
                }
                frequencyMap.put(nums[i], count);
                count = 1;
            }
        }
        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
            System.out.println(" Number :" + entry.getKey()
                    + " has frequence :" + entry.getValue());
        }
    }
}

带输出:

 Number :1 has frequence :1
 Number :2 has frequence :1
 Number :3 has frequence :2
 Number :4 has frequence :2
 Number :5 has frequence :3
于 2013-01-10T20:55:36.130 回答