AlgoMaster Logo
AlgoMasterDesign a Temperature Sensoreasy

Design a Temperature Sensor

easy

Design a TemperatureSensor class that records whole-number temperature readings while protecting its internal history. The sensor accepts only values within its supported range and provides simple statistics over the readings it has accepted.

Implement the TemperatureSensor class:

  • TemperatureSensor() creates a sensor with no readings.
  • boolean addReading(int value) records value and returns true when it is between -50 and 150, inclusive. An out-of-range value is rejected: the method returns false and leaves the stored readings unchanged.
  • int getReadingCount() returns the number of accepted readings.
  • double getAverage() returns the arithmetic mean of the accepted readings. If the sensor is empty, it returns 0.
  • int[] getReadings() returns the accepted readings in insertion order. It must return a new collection or array, so changing the result cannot modify the sensor's internal data.

Keep the readings encapsulated. Callers must be able to add values only through addReading, ensuring that the sensor can never store an out-of-range temperature.

Example 1:

Input:

Output:

Explanation: All three values are within the supported range, so the sensor stores them. Their arithmetic mean is (20 + 30 + 25) / 3 = 25.0.

Example 2:

Input:

Output:

Explanation: The sensor rejects -51 and 151 because they fall outside the inclusive range [-50, 150]. Only 100 is stored, so the count is 1 and the readings are [100].

Constraints:
  • -1000 <= value <= 1000
  • At most 100 calls will be made across all methods.

How the design is graded

needs 7/10 to pass
  • Encapsulation

    Full marks when the readings collection is private and getReadings hands back a copy, so a caller cannot mutate the sensor's own data through the returned value. Lose points for exposing the internal collection directly, or for any public field or setter that lets a caller bypass the range check.

  • Validation placement

    Full marks when the -50 to 150 inclusive range is enforced inside addReading, so the sensor cannot hold an out-of-range value regardless of how it is called. Lose points if the check is missing, if the bounds are exclusive, or if a rejected reading still changes the count.

  • Structure and naming

    Full marks for one cohesive class with descriptive names, an empty-collection average that is handled deliberately, and no dead code. Lose points for unused fields, printing to stdout, or logic unrelated to a sensor.

Passing every test is not enough on its own. A submission is accepted only when the design also clears the bar.

Hints

Loading...
CallReturns
new TemperatureSensor()null
addReading(20)true
addReading(30)true
addReading(25)true
getReadingCount()3
getAverage()25

All three readings are within the supported range. Their arithmetic mean is 25.

Run checks these cases. Submit also runs a larger hidden set.