Tableau Coding Round 1 - Air Quality sensor

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.7 kB
1
Indexable
Never
// Add a measurement to be tracked.
// Query for the worst-N measurements seen so far (at any time). (N=10K)
// air quality 
// 
// 
// Sensor 
// String name;
// String location;
// MaxHeap<Integer> airQualityHeap;  // Timestamp, QualityIndex, 
//
// addAirQuality();
// List<Integer> getWorstQualities(int n);



// Server
// 
// checkQuality(String sensorName, int n) 

import java.time.Instant;
import java.util.PriorityQueue;
import java.util.List;

public class Sensor {
    
    public class AirQuality {
        String timestamp;
        Double index;
        
        public AirQuality(String timestamp, Double index) {
            this.timestamp = timestamp;
            this.index = index;
        }
    }
    
    String name;
    String location; 
    PriorityQueue<AirQuality> airQualityHeap;
    
    public Sensor(String name, String location) {
        this.name = name;
        this.location = location;
        this.airQualityHeap = new PriorityQueue<>((aq1, aq2) -> aq2.index - aq1.index);
    }
    
    // called every minute
    public void addAirQuality(double airQuality) {
    
        Instant instant = Instant.now();
        
        AirQuality aq = new AirQuality(instant.toString(), airQuality);
        airQualityHeap.add(aq);     
    }
    
    public List<Double> getWorstQualities(int n) {
        int size = airQualityHeap.size();
        List<Double> worstQualities = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (i >= size) {
                break;
            }
            worstQualities.add(airQualityHeap.peek(i));
        }
        
        return worstQualities;        
    }
    
}