Don't miss your Year-End Offer: Up to 20% OFF

Program to Compute Average excluding Largest and Smallest Values

13 February 2024
import java.util.Arrays;

public class HackerAlgo {

    // Compute Average excluding Largest and Smallest Values
    public static double computeAverage(int[] arr) {
        int n = arr.length;

        if (n < 3) {
System.out.println("Array length should be at least 3 for computing average.");
            return 0.0;
        }

Arrays.sort(arr);
        double sum = 0;

        for (int i = 1; i< n - 1; i++) {
            sum += arr[i];
        }

        return sum / (n - 2);
    }

    public static void main(String[] args) {
        // Example for Compute Average excluding Largest and Smallest Values
int[] arr = {2, 6, 4, 9, 1, 5};
        double result = computeAverage(arr);
System.out.println("Average excluding largest and smallest values: " + result
# Compute Average excluding Largest and Smallest Values
def compute_average(arr):
    n = len(arr)

    if n < 3:
print("Array length should be at least 3 for computing average.")
        return 0.0

arr.sort()
    return sum(arr[1:-1]) / (n - 2)

# Example usage
arr = [2, 6, 4, 9, 1, 5]
result = compute_average(arr)
print("Average excluding largest and smallest values:", result)
#include <iostream>
#include <vector>
#include <algorithm>

class HackerAlgo {
public:
    // Compute Average excluding Largest and Smallest Values
    static double computeAverage(std::vector<int>& arr) {
        int n = arr.size();

        if (n < 3) {
std::cout<< "Array length should be at least 3 for computing average." <<std::endl;
            return 0.0;
        }

std::sort(arr.begin(), arr.end());
        double sum = 0;

        for (int i = 1; i< n - 1; i++) {
            sum += arr[i];
        }

        return sum / (n - 2);
    }
};

int main() {
    // Example for Compute Average excluding Largest and Smallest Values
std::vector<int>arr = {2, 6, 4, 9, 1, 5};
    double result = HackerAlgo::computeAverage(arr);
std::cout<< "Average excluding largest and smallest values: " << result << std::endl;

    return 0
class HackerAlgo {
    // Compute Average excluding Largest and Smallest Values
    static computeAverage(arr) {
const n = arr.length;

        if (n < 3) {
console.log("Array length should be at least 3 for computing average.");
            return 0.0;
        }

arr.sort((a, b) => a - b);
const sum = arr.slice(1, -1).reduce((acc, num) =>acc + num, 0);
        return sum / (n - 2);
    }
}

// Example usage
constarr = [2, 6, 4, 9, 1, 5];
const result = HackerAlgo.computeAverage(arr);
console.log("Average excluding largest and smallest values:", result);

Leave a Comment