查找数组中元素的平均值,并将平均值与数组中最接近的数字元素进行比较

时间:2017-04-05 11:15:41

标签: java arrays

将我的2d数组的平均元素与最接近的元素值进行比较时遇到一些问题。主要问题是我不知道如何继续使用math.abs将数组元素与平均值进行比较。

我的代码。

public class exercise_2{
public static int[] closestToMean (double[][] array)
{
    int sum = 0;
    for (int i=0; i < array.length; i++)
{
        for (int j=0; j < array.length; j++)
    {
        sum += array[i][j];
    }
}
    double mean = (double) sum / array.length;
    System.out.println("Mean = " + mean);
    //calculate mean of array elements i + j


    //closest to mean
    int distance = Math.abs(array[0] - mean);
    int i = 0;
    for (int c = 1; c < array.length; c++)
    {
        int cdistance = Math.abs(array[c] - mean);
        if (cdistance < distance)
        {
            i = c;
            distance = cdistance;
        }
    }
    double mean = array[i];
    System.out.println("Closest array element = " + mean);
    //print closest to mean array element
}

public static void testClosestToMean()
{
    exercise_2 ex2 = null;
    ex2.closestToMean();
    //invoke method closestToMean()
}

public static void main()
{
    exercise_2 ex2 = null;
    ex2.testClosestToMean();
    //invoke testClosestToMean()
}

}

1 个答案:

答案 0 :(得分:1)

以下代码应该执行您想要的操作:

@Test
public void test() {
  double[][] numbers = new double[][] {new double[] {1, 3, 5, 8}, new double[] {1, 2}};
  int[] indices = getClosestToMeanIndices(numbers);
  System.out.println("Closest element indices: " + indices[0] + ", " + indices[1]);
  System.out.println("Closest element: " + numbers[indices[0]][indices[1]]);
}

private int[] getClosestToMeanIndices(double[][] numbers) {
  if (numbers.length == 0) {
    throw new IllegalArgumentException("Input is empty");
  }

  // Calculate the mean
  double sum = 0;
  double elementCount = 0;
  for (double[] number : numbers) {
    for (double n : number) {
      sum += n;
      elementCount++;
    }
  }
  double mean = sum / elementCount;

  // Find closest index
  int[] indices = new int[] {-1, -1};

  double distance = Math.abs(mean - numbers[0][0]);
  for (int i = 0; i < numbers.length; i++) {
    for (int j = 0; j < numbers[i].length; j++) {
      double currentDistance = Math.abs(mean - numbers[i][j]);
      if (currentDistance < distance) {
        distance = currentDistance;
        indices[0] = i;
        indices[1] = j;
      }
    }
  }

  return indices;
}

<强>输出:

  

最近的元素索引:0,1   最近的元素:3.0

您在代码中忘记的是,您不仅需要使用数组的长度,还需要使用2D数组中完整数量的元素

最后,您可以检查距离并返回相应的指数。