Problem Statement: Average Temperature Calculation
You are tasked with implementing a Java method that calculates and prints the average temperature for each city from given arrays of cities and temperatures.
Constraints:
You are provided with two arrays:
String[] cities
: An array where each element represents the name of a city.
int[] temperatures
: An array where each element represents the temperature recorded for the corresponding city in the cities array.
The length of both arrays will be the same.
Duplicate city names may exist in the cities array, and the subsequent indices of temperatures should be considered for calculating the average temperature of each city.
Temperatures are represented as integers.
Example:
Given the following arrays:
String[] cities = {"New York", "Chicago", "New York", "Chicago", "Los Angeles"};
int[] temperatures = {75, 70, 80, 72, 85};
Your method should output:
Average temperature in New York: 77.5
Average temperature in Chicago: 71.0
Average temperature in Los Angeles: 85.0
Solution
// a Pair class in created to keep track of total temperatures and sum of temperature
private static class Pair{
public int temperature;
public int total;
public void addNewTemperature(int temperature ){
this.temperature = this.temperature +temperature ;
this.total = this.total+1;
}
public double calculateAvgTemperature()
{
return (double) temperature / total;
}
}
private static void printAverageTemperature(String[] cities, int[] temperatures)
{
Map<String,Pair> citiesMap = new HashMap<>();
for (int i = 0; i < cities.length; i++) {
String currentCity = cities[i];
// fetch existing pair or create new for current city
Pair pair = citiesMap.get(currentCity) == null ? new Pair() : citiesMap.get(currentCity);
// this will add new temperature to exiting, and increment total by 1
pair.addNewTemperature(temperatures[i]);
// add pair obj to map
citiesMap.put(currentCity,pair);
}
citiesMap.forEach( (key,pair)->{
System.out.println(key +": "+pair.calculateAvgTemperature());
});
}
Top comments (0)