问题
I want to create a program to help me with the statistics, but I'm having problems from the beginning and I'm making a huge mess to calculate the relative frequency of an array with random numbers and only one dimension.
For example to generate these numbers:
{3, 5, 5, 2, 4, 1, 3, 5, 4}
I want that the program tell me that the 3
is repeated 2 times, the 4
3 times and 5
5 times
I've created a class to sort these values in order to calculate the median, the first and third quartile, but I still do not know how to find the frequency in order to calculate other values
Thanks for your time
PS: Do not know if this affects anything but I'm using netbeans
回答1:
You are looking for this for sure: Collections: frequency
If you dont have a Collection, convert your array to list first:
Collections.frequency(Arrays.asList(yourArray), new Integer(3))
回答2:
If your range of numbers is relatively small, using an array of counters could be preferred.
For example, if your random numbers are in the interval [1,5]
then you can use an array of size 5 to store and update the frequency counters:
int[] numbers = {3, 5, 5, 2, 4, 1, 3, 5, 4} ;
int[] frequencies = new int[5];
for(int n : numbers)
frequencies[n-1]++;
Output array (frequencies
):
1 1 2 2 3
EDIT:
This method can be applied to all ranges. For example, let's say you have numbers in the range [500,505]
:
int[] frequencies = new int[6];
for(int n : numbers)
frequencies[n-500]++;
回答3:
Edit: You can use a map for storing frequency like below :
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());
}
}
}
With Output :
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
回答4:
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());
}
来源:https://stackoverflow.com/questions/14266989/relative-frequency-in-java