cppintermediate10 minutes

Refactor Messy C++ Code for Calculating Statistics on an Integer Array

Improve and clean up a provided C++ function that calculates the minimum, maximum, and average of an integer array while maintaining the same behavior.

Challenge prompt

Given the provided C++ function messyStats, refactor the code to improve readability, efficiency, and maintainability without changing its output or behavior. The function takes a vector of integers and returns a tuple containing the minimum value, maximum value, and average (as a double) of the integers in the vector. Keep the same function signature and behavior, but improve variable naming, reduce redundancies, and structure the logic more cleanly.

Guidance

  • Focus on improving variable names and removing unnecessary variables or repeated computations.
  • Consider early exits or handling edge cases more cleanly, such as empty input.
  • Consolidate loops if possible to improve efficiency.

Hints

  • Use descriptive variable names like minVal and maxVal instead of single letters.
  • Calculate sum, min, and max in a single pass instead of multiple loops.
  • Handle the empty vector case before processing to avoid undefined behavior.

Starter code

#include <vector>
#include <tuple>
#include <limits>

std::tuple<int, int, double> messyStats(const std::vector<int>& nums) {
    if (nums.size() == 0) {
        return std::make_tuple(0, 0, 0.0);
    }
    int a = nums[0];
    int b = nums[0];
    int c = 0;
    for (int i = 0; i < (int)nums.size(); i++) {
        if (nums[i] > b) {
            b = nums[i];
        }
    }
    for (int i = 0; i < (int)nums.size(); i++) {
        if (nums[i] < a) {
            a = nums[i];
        }
    }
    for (int j = 0; j < (int)nums.size(); j++) {
        c += nums[j];
    }
    double d = (double)c / (double)nums.size();
    return std::make_tuple(a, b, d);
}

Expected output

For input {4, 8, 6, 3, 9}: (3, 9, 6.0) For empty input {}: (0, 0, 0.0)

Core concepts

Code RefactoringLoopsVariable NamingEfficiency

Challenge a Friend

Send this duel to someone else and see if they can solve it.