简体   繁体   中英

How to create a temporary list from a 2d array to calculate a median?

I need to create a class ArrayMethods. With a • public static double median(double[][] a) method. I know that i need to create a list with all the values from the 2d arrays. Then sort it out and find the median. BUt I dont know how to create a list. Can anyone help me with this. For the median, I have done this but it doesn't work on negative numbers or odd number of arrays:-

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;
   }

}

If we're talking about simply creating a list, then we will need a dynamic list able to store whatever number of values, since we only know the size of the array if we either hard-code it (never!) or at runtime. The best solution for this is a basic ArrayList.

First, we store all the values into the ArrayList, and once all values are stored, we can then sort it. As you know, it's all down hill from there. The median (using your implementation of the median) can be found now using:

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);
}

I also threw in the check for an empty array, but if you want to get rid of it you can. Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM