二维数组中的双中值计算
double median calculation in 2 d Array
我必须实现一个静态 public 方法 在 class “Functionality.java方法获取一个二维双精度数组作为输入参数,returns 一个双精度值。
签名:medianInception(double[][] array) : double
首先要计算子阵列的中值。请注意,这些可以未排序!
要对单个数组进行排序,请使用 BubbleSort、InsertionSort 或 SelectionSort。然后将它们的中位数输入到一个新的(一维)数组中,该数组又会再次计算中位数,然后 returns 它。如果其中一个数组为 null 或空,则返回 Double.NaN。
查询数组是否为零或空时,必须始终先查询零,否则会出现NullPointerException!
我可以使用数学库
我的代码:
public static double median(int[] m) {
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
我的问题:这是计算一维数组中的中位数。但我就是不知道如何为 2d 实现它。我还想要每个子数组的中位数。
My problem: This would be the calculation of the median in a
one-dimensional array. But I just cannot figure out how to implement
this for a 2d. I also want the medians of each subarray.
二维数组是一维数组的数组。您需要做的就是迭代二维数组并将每一行的中位数存储到一维数组中。
public static double[] median(int[][] m) {
double[] result = new double[m.length];
for (int i = 0; i < m.length; i++) {
int middle = m[i].length / 2;
if (m[i].length % 2 == 1) {
result[i] = m[i][middle];
} else {
result[i] = (m[i][middle - 1] + m[i][middle]) / 2.0;
}
}
return result;
}
我必须实现一个静态 public 方法 在 class “Functionality.java方法获取一个二维双精度数组作为输入参数,returns 一个双精度值。
签名:medianInception(double[][] array) : double
首先要计算子阵列的中值。请注意,这些可以未排序!
要对单个数组进行排序,请使用 BubbleSort、InsertionSort 或 SelectionSort。然后将它们的中位数输入到一个新的(一维)数组中,该数组又会再次计算中位数,然后 returns 它。如果其中一个数组为 null 或空,则返回 Double.NaN。
查询数组是否为零或空时,必须始终先查询零,否则会出现NullPointerException!
我可以使用数学库
我的代码:
public static double median(int[] m) {
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
我的问题:这是计算一维数组中的中位数。但我就是不知道如何为 2d 实现它。我还想要每个子数组的中位数。
My problem: This would be the calculation of the median in a one-dimensional array. But I just cannot figure out how to implement this for a 2d. I also want the medians of each subarray.
二维数组是一维数组的数组。您需要做的就是迭代二维数组并将每一行的中位数存储到一维数组中。
public static double[] median(int[][] m) {
double[] result = new double[m.length];
for (int i = 0; i < m.length; i++) {
int middle = m[i].length / 2;
if (m[i].length % 2 == 1) {
result[i] = m[i][middle];
} else {
result[i] = (m[i][middle - 1] + m[i][middle]) / 2.0;
}
}
return result;
}