我想创建一个程序来帮助我统计数据,但是我从一开始就遇到了问题而且我在计算具有随机数且只有一个维度的数组的相对频率时发生了巨大的混乱。
例如,要生成这些数字:
{3,5,5,2,4,1,3,5,4}
我希望该程序告诉我3
重复2次,4
3次,5
5次
我创建了一个类来对这些值进行排序,以便计算中位数,第一和第三四分位数,但我仍然不知道如何找到频率以计算其他值
感谢您的时间
PS:不知道这会影响到什么,但我正在使用 netbeans
答案 0 :(得分:3)
您正在寻找这个:Collections: frequency
如果您没有Collection,请先将数组转换为list:
Collections.frequency(Arrays.asList(yourArray), new Integer(3))
答案 1 :(得分: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]++;
答案 2 :(得分: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
答案 3 :(得分: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());
}