java - Determine sum of specific elements within an array -
i have array, stores series of doubles inputted user. length of array user's choice, , therefore varies. put numbers loop, calculates average , swaps outlier last index of array. new average calculated without outlier , new outlier swapped second last index of array. cycle repeated until 1 element remains.
however outlier not removed array, need calculate average somehow without outlier. thinking specify index of elements want include in average.
it seems process should this:
- compute average traversing array till n elements.
- find outlier.
- swap last element.
- now set n (current size of array - 1). , keep on doing till size = 0;
i have compiled code may work you. keep in mind may need make small changes per requirement.
public static void main(string[] args) throws filenotfoundexception { double[] dataarray = new double[] {1.5,2.5,3.5,4.5,7.5,8.5,2.5}; int arraysizetoconsider = dataarray.length; double outlier; int index_outlier; double avg; double diffinoutlierandavg; while(arraysizetoconsider > 0) { outlier = dataarray[0]; index_outlier = 0; avg = computesum(dataarray,arraysizetoconsider) / (arraysizetoconsider);//avg of elements diffinoutlierandavg = math.abs(avg - outlier); // find outlier for(int index = 0; index<arraysizetoconsider; index++)//increments index { if(math.abs(avg - dataarray[index]) > diffinoutlierandavg) { outlier = dataarray[index]; index_outlier = index; } } double temp = dataarray[arraysizetoconsider -1]; dataarray[arraysizetoconsider -1] = outlier; dataarray[index_outlier] = temp; arraysizetoconsider = arraysizetoconsider -1; system.out.println("average: " + avg + " outlier: " + outlier + " index " + index_outlier + " array size consider: " +arraysizetoconsider); } } private static double computesum(double[] array, int arraysizetoconsider) { double sum = 0; (int = 0; < arraysizetoconsider; i++) { sum = sum + array[i]; } return sum; }
and here output:
average: 4.357142857142857 outlier: 8.5 index 5 array size consider: 6 average: 3.6666666666666665 outlier: 7.5 index 4 array size consider: 5 average: 2.9 outlier: 4.5 index 3 array size consider: 4 average: 2.5 outlier: 1.5 index 0 array size consider: 3 average: 2.8333333333333335 outlier: 3.5 index 2 array size consider: 2 average: 2.5 outlier: 2.5 index 0 array size consider: 1 average: 2.5 outlier: 2.5 index 0 array size consider: 0
there improvements can made , have skipped them. need figure out :)
Comments
Post a Comment