[英]How to create a temporary list from a 2d array to calculate a median?
我需要创建一个类ArrayMethods。 •使用公共静态双位数(double [] [] a)方法。 我知道我需要使用2d数组中的所有值创建一个列表。 然后将其分类并找到中位数。 但是我不知道如何创建列表。 谁能帮我这个。 对于中位数,我已经做到了,但不适用于负数或奇数数组:-
public static void main(String[] args) {
double[][] a = {
{1,2,3},
{4,5,6},
};
System.out.println(median(a));
}
public static double median(double[][] a2) {
double[] list = new double[a2.length*a2[0].length];
double listPos = 0;
for(double i = 0 ; i < a2.length; i++) {
for(double j = 0; j < a2[(int) i].length; j++) {
list[(int) listPos++] = a2[(int) i][(int) j];
Arrays.sort(a2[(int) i]);
}
}
double middle = list.length/2;
if ((list.length%2) == 1) {
return list[(int) middle];
}
return (list[(int) (middle-1)] + list[(int) middle]) / 2.0;
}
}
如果我们只是在谈论创建一个列表,那么我们将需要一个能够存储任意数量值的动态列表,因为我们只有在硬编码(从不!)或在运行时才知道数组的大小。 最好的解决方案是基本的ArrayList。
首先,我们将所有值存储到ArrayList中,一旦存储了所有值,便可以对其进行排序。 如您所知,那里到处都是山。 现在可以使用以下方法找到中位数(使用中位数的实现):
public static double median(double[][] a2) {
// check for an empty array
if(a2.length == 0)
throw new IllegalStateException("The array is empty");
ArrayList<Double> list = new ArrayList<Double>();
// first, add all the elements into the linear list
for(int i = 0; i < a2.length; i++) {
for(int j = 0; j < a2[0].length; j++) {
list.add(a2[i][j]);
}
}
// second, sort them
Collections.sort(list);
// and finally, determine the median based on the number of items
int length = list.size();
// if there is an even number of values, take the average of the 2 middle values
if(length % 2 == 0)
return (list.get(length/2 - 1) + list.get(length/2)) / 2.0;
// else, return the middle value
return list.get(length / 2);
}
我还检查了一个空数组,但是如果您想摆脱它,可以这样做。 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.