Sobes.tech
Junior — Senior

Optimization and refactoring of the maximum time calculation function

livecode

Task condition

The task requires improving the structure and readability of the existing code responsible for calculating the maximum time needed for a set of devices to cover a given distance S. Below is the original C code fragment that needs to be analyzed and refactored for clarity while preserving its functionality.

/*
There are several devices, connected in chain like this:

start_idx---|
            |
D - D - D - A - A - A - A - B - B - D - D
            |-------- N --------|

The task is to get the speeds of N devices and calculate the maximum time to traverse some distance S.
*/

#define A 4
#define B 2

#define N A + B

// Function to get the speed of a device with index `idx`
double get_motor_speed(int idx);

static float counter = 0;

// Function to calculate the maximum time for the motors to traverse distance `S`
double calc_max_time(double S, int start_idx)
{
    double t[N];
    for (int i = 0, n = start_idx; i < N; i++, n++)
    {
        double v = get_motor_speed(n);
        counter += 1;

        if (v == 0)
            printf("error, can't divide by zero\n");
        else
        {
            printf("%f\n", S / v);
            t[i] = S / v;
        }
    }

    double result = 0;

    for (int i = 0; i < N; i++)
    {
        if (t[i] > result)
            result = t[i];
    }

    return result;
}

Requirements:

  • Remove code duplication,
  • Extract constants and calculations into separate functions/structures,
  • Ensure clearer variable names and comments,
  • Minimize the use of global state (counter).

The resulting code should be easier to maintain and test while preserving the original business logic.