Here are fragments of the code I have so far. My problem is that the min values come up as Integer.MAX_VALUE, instead of the value I want. iSpeedMph and pressure are both one-dimensional integer arrays.
//calculating mins
Integer min = Integer.MAX_VALUE;
int minSpeed = Integer.MAX_VALUE;
int minPressure = Integer.MAX_VALUE;
for(i = 0; i < iSpeedMph.length; i++)
{
if (min > iSpeedMph[i])
{
min = iSpeedMph[i];
minSpeed = iSpeedMph[i];
}
}
min = Integer.MAX_VALUE;
for(i = 0; i < pressure.length; i++)
{
if (min > pressure[i])
{
min = pressure[i];
minPressure = pressure[i];
}
}
...
System.out.printf("%7s%2s%-9s%4s%8s%5s%13.3s%5s%16.2s\n", "Minimum", " ", " ", " ", " ", " ", minPressure, " ", minSpeed);
When I print out the last line, the terminal shows 214 for pressure and 21 for speed, which, without the formatting, means that they are both Integer.MAX_VALUE.
You are checking if the current item is greater than the current min, which is Integer.MAX_VALUE, but you want to check if the current item is less than the current min instead, e.g.
if (iSpeedMph[i] < min)
and likewise for the other min determinations.
The test
if (iSpeedMph[i] > min)
always returns false. You have to reverse the comparison.
if (iSpeedMph[i] < min)
or as alternative
if (min > iSpeedMph[i])
The below condition will never become true for any integer, since min is Integer.MAXVALUE.
if (iSpeedMph[i] > min)
just initialize it 0, to check if you are searching min of all in array or, assign min with first array value and loop the array from 2nd element.
if (iSpeedMph[i] > min) how could this give you the new min value?
Also, please use min methods already written for you, e.g. https://stackoverflow.com/a/1658144/499922
As others have pointed out you have the comparison in the if statements wrong. But finding min and max in arrays is very simple with Java 8 streams :
int minSpeed = Arrays.stream(iSpeedMph).min().get();
int minPressure = Arrays.stream(pressure).min().get();
Related
I am trying to find an index of a number in array. I am using varargs method.
My task was to find minimum of numbers and then find his position.
public static void main(String[] args) {
System.out.println(minimum(2.4, 4.5, -11.3, 3.9, -7.2, -12.1, 14.8));
}
public static double minimum(double... n) {
int k = 0;
double min = n[k];
for (double i : n) {
k++;
if (i < min) {
min = i;
}
if (min == n[k - 1]) {
System.out.println("minimum number index is " + (k - 1));
}
}
return min;
Outcome is this
index of minimum: 0
index of minimum: 2
index of minimum: 5
-12.1
When i put System.out.print outside of for loop printing last value for k. Thank you in advance.
Hope this helps. Just got to keep the min index in a variable just like storing min value.
public static double minimum(double... n) {
int k = 0;
double min = n[k];
minIndex = k;
for (double i : n) {
k++;
if (i < min) {
min = i;
minIndex = k-1;
}
}
System.out.println("minimum number index is " + (minIndex));
return min;
}
You are almost there !
As you correctly recognized, your variable k holds the index + 1 of the double you are looking at in your for loop.
If you want to keep the index of the smallest value in the array, you need to do the same thing you did with variable min. You need an additional variable which you initialize outside the loop. When you find a new "smaller value" in the array, you store the k-1 in this variable.
When you exit the for loop, that variable will hold the index of the smallest value in the array.
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):
Create a minimum and maximum value to store the index of the min and
max, respectively (can be initialized to 0 and 0)
Loop through each element of the temperatures array
For each element, if it is less than the element at min, change min to the current index
If it is greater than the element at max, change max to the current index
Once you finish, you will have indexes in which the difference is greatest, simply add one to get the day.
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+1s 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.
I am doing some exercises on codingbat because I have been struggling with arrays. The question was:
"Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more."
I was able to code the solution correctly except for 1 part.
The correct code is:
public int centeredAverage(int[] nums) {
int max = nums[0];
int min = nums[0];
int add = nums[0];
for(int i = 1; i < nums.length; i++){
add += nums[i];
if(nums[i] > max){
max = nums[i];
}
else if(nums[i] < min){
min = nums[i];
}
}
return (add - max - min) / (nums.length - 2);
}
My question is why are we starting at int i = 1 rather than 0? If you start at 1 aren't you skipping over a cell?
The initialization:
int max = nums[0];
int min = nums[0];
int add = nums[0];
handles the case when i = 0 for you.
As you are setting max, min and add from zero index of array.By doing this u are finding min and max from a single loop iteration(i.e.. by compairing this values from the other elements of array). If u havn't done this then u have to use some other logic to find min and max of array like O(n)^2 soln.
I have an array that has around 1000 entries, these are split up into 12 entries per year, I'm trying to find the maximum value for each year, to do so I need to read 12 values at a time and find the maximum value of those 12, and then move on to the next 12 values from the array, and so on until it is complete.
Trying to do this I made a temporary array to store the 12 values in, as well as the final array with the max score per year. The code below doesn't work and i'm unsure why, I have spent quite a while researching and attempting this with different solutions, any help will be appreciated :)
//double rain[]= new double [1268]; this is the array declared earlier with data in
double maxRAINyear[]= new double [1200];
double temp [] = new double [12];
int arrayCounter = 0;
int count = 0;
for (int c = 36; c < rain.length; c++) {
temp[count] = rain[c];
if (count == 12){
Arrays.sort(temp);
double max = temp[temp.length - 1];
maxRAINyear[arrayCounter] = max;
arrayCounter++;
count = 0;
}
count++;
}
It's difficult to see what's wrong with your code without knowing what it produces, but in any case this isn't a great way to do this.
I'll assume that you are constrained to the input format of one long array, even though a multidimensional array might make more sense depending on what else it's used for.
// double rain[] = new double[1268]; // input
double maxRAINyear[] = new double[(rain.length+11) / 12];
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < rain.length; i++)
{
if (rain[i] > max) max = rain[i];
if (i % 12 == 0)
{
maxRAINyear[i / 12] = max;
max = Double.NEGATIVE_INFINITY;
}
}
if (rain.length % 12 != 0) maxRAINyear[maxRAINyear.length-1] = max;
This calculates the maximum of each 12 numbers as it goes, rather than storing them separately and sorting them. I've assumed there are a whole number of years stored. If you want to account for a partial year at the end this will need to be modified.
I implemented it without a temporary array, but by just iterating over the array. That should be more efficient.
int amountOfYears = rain.length/12-3;
double maxRAINyear[]= new double [amountOfYears];
for(int i=0;i<amountOfYears;i++){
//Find maximum for these 12 indixes
double max = Double.NEGATIVE_INFINITY;
for(int j=12*i+36;j<12*(i+1)+36;j++){ //use 12*i as an offset, that way, you don't need a temp array
if(rain[j] > max)
max = rain[j];
}
//store maximum
maxRAINyear[i] = max;
}
If you also need to find the partial year, use this
int amountOfYears = Math.ceil(rain.length/12f)-3;
double maxRAINyear[]= new double [amountOfYears];
for(int i=0;i<amountOfYears;i++){
//Find maximum for these 12 indixes
double max = Double.NEGATIVE_INFINITY;
int start = 12*i+36;
int end = Math.min(rain.length,12*(i+1)+36);
for(int j=start;j<end;j++){ //use 12*i as an offset, that way, you don't need a temp array
if(rain[j] > max)
max = rain[j];
}
//store maximum
maxRAINyear[i] = max;
}
When count is 11, you are incrementing it to 12 and going into the next round of the loop. Now temp[count] = rain[c]; will attempt to store a value into index 12 of temp, but there are only 12 entries with indices 0 through 11. So I suspect you are getting an ArrayIndexOutOfBoundsException.
I believe you should move count++ before the if statement. This way a count of 12 will be reset to 0 before it creates any havoc.
This solution have the advantage to work if the array length is not a multiple of the range without doing to many check.
public static double[] read(double[] array, int range) {
double[] result = new double[array.length / range + (array.length % range > 0 ? 1 : 0 )]; //Just add one cell if the length is not a multiple of the range
double max = array[0];
int i = 1;
while (i < array.length) {
if (i % range == 0) { //Next range
result[i / range - 1] = max; //Save last
max = array[i]; //Get current
} else if (array[i] > max) {
max = array[i];
}
++i;
}
result[result.length - 1] = max; //for the last range
return result;
}
I've looked at the answer posted here (finding smallest and second smallest number) but I cannot get my code to work.
Here is what I have.
public static void shortestTimes(int[] times){
int counter = 0;
int secondLowest = times[counter];
int min = times[counter];
for (counter = 0; counter < times.length; counter ++) {
if (times[counter] < min) {
secondLowest = min;
min = times[counter];
} else if (times[counter] < secondLowest) {
secondLowest = times[counter];
}
}
System.out.println("The fastest time was: " + min + ". And the second fastest was: " + secondLowest);
}
When I put in the input:
int[] values = {1, 3, 3, 2, 5};
longestTimes(values);
I get the output:
The fastest time was: 1. And the second fastest was: 1
Why is my second lowest number not getting changed?
Your second lowest value is not getting changed because from the beginning you are setting secondLowest to be equal to the value at values[0], which is your lowest value in the array. If I were you, I would initialize both min and secondLowest to Integer.MAX_VALUE. Then the algorithm would behave as expected
Firstly when you declare min and secondLowest I would check if times.length >= 2.
I would then assign them with:
min = times[0];
secondLowest = times[1];
The problem is with your declaration of secondLowest and the fact that they both start at the lowest value. You don't have any sort of check to see if min and secondLowest are referring to the same number within the array.
If the array is guaranteed to contain unique values this isn't an issue, but if not you should change around your search. Sorting the array would help too.