Hey Stackoverflow Community, I got a little problem where I´m stuck at the moment.. I have to write a code, that have to find the biggest " temperature " difference between given days. These are my Arrays:
int[] day = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
int[] temperature = {12,14,9,12,15,16,15,15,11,8,13,13,15,12,12,11,7,13,14,11,9,11,10,7,11,6,11,15,10,7};
I need to have an Output like: The biggest temperature difference was between Day X and Day X with the difference of X Degrees Can someone give me a hint whats the best way to do it?
Cheers
Hint: A good way to do it in one pass is to keep track of a minimum and maximum, and use those somehow.
More in depth (Don't read if you want to figure it out yourself):
Here's some java code:
void greatestDifference(int[] day, int[] temperature) {
int min = 0;
int max = 0;
for(int i = 0; i < temperature.length; i++) {
if (temperature[i] < temperature[min]) {
min = i;
} else if (temperature[i] > temperature[max]) {
max = i;
}
}
int difference = temperature[max] - temperature[min];
System.out.println("The biggest temperature difference was between Day " + (min+1) + " and Day " + (max+1) + ", with the difference of " + difference + " Degrees.");
}
Hope this helped!
Edit: If you plan on having values in day[]
that aren't just 1, 2, 3, etc., you can replace the i+1
s in the print statement to day[min]
and day[max]
to get the specific days at which it held those min and max values.
Also, as @SirRaffleBuffle pointed out, the index in the for loop can start at one, since the values at zero would only compare to themselves, but this is not necessary.
Edit 2: The problem seems to actually have been to find the greatest difference between consecutive days. No worries! Here's some code for that:
import java.lang.Math;
void greatestDifference(int[] day, int[] temperature) {
int max = 0;
for(int i = 0; i < temperature.length-1; i++) {
if (abs(temperature[i] - temperature[i+1]) > abs(temperature[max] - temperature[max+1])) {
max = i;
}
}
int difference = temperature[max+1] - temperature[max];
System.out.println("The biggest temperature difference was between Day " + (max+1) + " and Day " + (max+2) + ", with the difference of " + difference + " Degrees.");
}
This just loops through each value in temperatures
and finds the difference between it and the temperature the next day. If the difference is greater than the current max, we update the max. P.S. Math.abs()
finds the absolute value.