Fix the average of a run of sensor readings
Your task
Your firmware team averages sensor readings that are unsigned 32-bit integers. The first Rust version summed them into a u32, which panics in debug builds and silently wraps around in release builds once the total passes 4294967295. It also divided by zero on an empty list.
An assistant wrote average_reading(readings) to fix both. It is in the editor. It has a bug. Find it and fix it.
Input and output:
readings: the readings, each a whole number from 0 to 4294967295.- Return the average as an integer, or -1 when there are no readings.
Rules the tests check:
- An empty list returns -1.
- Otherwise return the exact sum of all readings divided by their count, rounded down. The sum can be far larger than 4294967295 and must not wrap.
Examples
average_reading(readings: list[int]) -> intExample 1
Input
average_reading([10, 20, 30])Output
20Example 2
Input
average_reading([])Output
-1Example 3
Input
average_reading([4294967295, 4294967295, 4294967295, 4294967295])Output
4294967295