(Java Programming) Lies, D@^# Lies, and Statistics Write a class AveragingNumber
ID: 3595423 • Letter: #
Question
(Java Programming)
Lies, D@^# Lies, and Statistics
Write a class AveragingNumbers with the following static methods
// The following method takes the original array, and
// uses Arrays.sort to create a new, sorted array.
// original is not modified in any way.
public static double[] loToHi(double[] original)
// The following method takes the original array, and
// returns a new array sorted starting with the highest number.
// The original array is not modified in any way.
// Hint: you can call loToHi to make life easier in this method.
public static double[] hiToLo(double[] original)
// The following method returns the average of the given array
public static double avg(double[] original)
Explanation / Answer
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class AveragingNumbers {
// The following method takes the original array, and
// uses Arrays.sort to create a new, sorted array.
// original is not modified in any way.
public static double[] loToHi(double[] original) {
double[] dest = new double[original.length];
System.arraycopy( original, 0, dest, 0, original.length );
Arrays.sort(dest);
return dest;
}
// The following method takes the original array, and
// returns a new array sorted starting with the highest number.
// The original array is not modified in any way.
// Hint: you can call loToHi to make life easier in this method.
public static double[] hiToLo(double[] original) {
double[] dest = loToHi(original);
for (int i = 0; i < dest.length / 2; i++) {
double temp = dest[i];
dest[i] = dest[dest.length - 1 - i];
dest[dest.length - 1 - i] = temp;
}
return dest;
}
// The following method returns the average of the given array
public static double avg(double[] original) {
double avg = 0;
for (int i = 0; i < original.length; i++) {
avg += original[i];
}
return avg/original.length;
}
public static void main(String[] args) {
double original[] = new double[1000000];
Random r = new Random();
for (int i = 0; i < original.length; i++)
original[i] = r.nextDouble();
double averageRandom = avg(original);
double sortedOriginal[] = loToHi(original);
double averageLoToHi = avg(sortedOriginal);
double sortedROriginal[] = loToHi(original);
double averageHiToLo = avg(sortedROriginal);
System.out.println("Average is " + averageRandom);
System.out.println("Lo to hi Average is " + averageLoToHi);
System.out.println("Hi to lo Average is " + averageHiToLo);
if (averageLoToHi != averageHiToLo || averageHiToLo != averageRandom) {
System.out.println("Averages are not equal");
}
else {
System.out.println("Averages are not identical");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.