[英]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.