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.
Related
I'm a beginner at java and was wondering on how to find the maximum difference between numbers inputted into a for loop. My program takes x amount of odometer readings (Between consecutive trips) from a car, e.g 100km, 150km, 400km, and is supposed to take the maximum distance traveled for all trips, which in this example would be 250km, as well as the minimum which would be 50km and average distance traveled between each odometer reading.
So far i've only managed to find a way to calculate the biggest value and smallest value for each odometer reading, given by the variables maximum and minimum, however have no idea on how to approach or begin to program finding the difference between trips. I tried implementing an array of some sort (not shown in this code) but i keep receiving too many errors. I could really use some advice on how to approach this problem or some insight; it would be greatly appreciated. Thank you for your time.
System.out.print("Input number of trips: ");
carSample.numberOfTrips = input.nextInt();
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
int total = 0;
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i + 1) + ": ");
int odometerReading = input.nextInt();
total += odometerReading;
if (odometerReading > maximum){
maximum = odometerReading;
}
if (odometerReading < minimum){
minimum = odometerReading;
}
int previous = 0;
int minimumTrip = Integer.MAX_VALUE;
int maximumTrip = Integer.MIN_VALUE;
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i + 1) + ": ");
int odometerReading = input.nextInt();
int currentTrip = odometerReading - previous;
if (currentTrip > maximumTrip){
maximumTrip = currentTrip;
}
if (currentTrip < minimumTrip){
minimumTrip = currentTrip;
}
previous = odometerReading;
}
If reading starts not from 0 consider previous = first odometer reading
If you want to calculate the maximum and minimum values of each mileage, the initial values of both are 0, and the maximum and minimum values are updated every time a mileage value is read, and all the mileage values can be obtained by looping .
If you want to calculate the average of all mileage values, then add up all the values divided by the number of values
For example, av = (a + b + c) / 3
I am really new to java and I signed up for an AP class which is being taught very badly, and so I have no idea of how to do this part of the assignment. It prampts you to add code that will do the following
Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., “Salesperson 3 had the highest sale with $4500.” Note that you don’t need another loop for this; you can do it in the same loop where the values are read and the sum is computed.
the code we are given is the following
import java.util.Scanner;
public class Sales {
public static void main(String[] args) {
final int salesPeople = 5;
int[] sales = new int[salesPeople];
int sum;
Scanner scan = new Scanner(System.in);
for (int i=0; i<sales.length; i++) {
System.out.print("Enter sales for salesperson " + i + ":");
sales[i] = scan.nextInt();
}
System.out.println("\nSalesperson Sales");
System.out.println("------------------");
sum = 0;
for (int i=0; i<sales.length; i++) {
System.out.println(" " + " " + sales[i]);
sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
System.out.println("Average sale " + sum/salesPeople);
}
}
I really do not know what to do and would appreciate a nudge in the right direction as to how to find the max and the id of the person who produced the max.
Please help this is homework!
Because it's your homework, I won't give you the direct answer, but instead give you some hints. If you add two variables, say,
int heighestSale = -1; // assume the sales are not negative or at least one sale is not negative
int heighestPerson = -1;
then you update the two variables based on the current sale value in one of the loops and print out them at the end.
One possible strategy for finding a max value of an unsorted array is to go through the array (using a for loop, perhaps), and keeping track of the maximum value as you go through it.
I don't want to do your homework, but that might look like:
max = Integer.MIN (the smallest possible integer value)
for item in array
if item is greater than max
store item in max
This strategy should find the max value -- hope this helps you! Model the for loops and the print statements like the previous ones you've shown.
The key here is to remember that the sum of all sales and max number of sales can be calculated each time a new salesman's entry is inputted. On the first entry, for example, salesman 0 has N sales -- therefore the sum is N and the max is N. On each consecutive entry, you can update the sum by adding the value to it, and you can update the max if the entry's value is greater than the currently known maximum.
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();
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm very new here,
at the moment I am trying to calculate standard deviation with Java (I have googled it haha)
but I am having a lot of issues on getting it working
I have ten values that are inputed by a user which I then have to calculate the standard deviation of
my understanding so far thanks to people who have replied
is
I find the mean of the array
then complete the calculations
double two = total[2];
double three = total[3];
double four = total[3];
double five = total[4];
double six = total[6];
double seven = total[7];
double eight = total[8];
double nine = total[9];
double ten = total[10];
double eleven = average_total;
mean = one + two + three + four + five + six + seven + eight + nine + ten + eleven;
mean = mean/11;
//one = one - mean;
//System.out.println("I really hope this prints out a value:" +one);
*/
//eleven = average_total - mean;
//eleven = Math.pow(average_total,average_total);
//stand_dev = (one + two + three + four + five + six + seven + eight + nine + ten + eleven);
//stand_dev = stand_dev - mean;
// stand_dev = (stand_dev - mean) * (stand_dev - mean);
// stand_dev = (stand_dev/11);
// stand_dev = Math.sqrt(stand_dev);
I already have my data that is stored in an array of 10 values but I am not too sure
how to print the data out of the array then do the calculations with out having to store the enter code here
data some where else that I have manipulated
Thank you for your time, much appreciated :)
There is a simple formula that can be used to quickly calculate standard deviation every time a number is added. Here is some code that implements that formula, assuming total[] has been declared and populated already:
double powerSum1 = 0;
double powerSum2 = 0;
double stdev = 0;
for i = 0 to total.length {
powerSum1 += total[i];
powerSum2 += Math.pow(total[i], 2);
stdev = Math.sqrt(i*powerSum2 - Math.pow(powerSum1, 2))/i;
System.out.println(total[i]); // You specified that you needed to print
// each value of the array
}
System.out.println(stdev); // This could also be placed inside the loop
// for updates with each array value.
The beauty of this formula is that you don't have to reprocess the entire array each time you add a new value and you don't have to store any of the old values of the array, just the three variables declared in the code above.
calculate mean of array.
loop through values
array value = (indexed value - mean)^2
calculate sum of the new array.
divide the sum by the array length
square root it
edited:
I'll show you how to loop through the array and everything is pretty much this same step just with a different calculation.
// calculating mean.
int total = 0;
for(int i = 0; i < array.length; i++){
total += array[i]; // this is the calculation for summing up all the values
}
double mean = total / array.length;
edit2:
After reading your code, the part you are doing wrong is that you are not looping through the values and subtracting it with average correctly.
aka this part.
eleven = average_total - mean;
eleven = Math.pow(average_total,average_total);
you need to do this.
for(int i = 0; i < array.length; i++){
array[i] = Math.pow((array[i]-mean),2)
}
essentially you need to change every value in the array with newvalue = oldvalue - mean(average).
then calculate the sum... then square root that.
I won't solve your problem for you since this looks like howework, but I'll try to help you out a little by giving you some pseudocode to point you in the right direction:
Loop over array i=1 to 10
Add each element to some other variable Total
End of Loop
Average = Total / 10 (required for your std. dev. equation)
Now you need to find the distances of the elements from the mean. Easy
Loop over array i = 1 to 10
Replace each element with its distance from Average Squared
Add to some variable differenceTotal
End of Loop
Then you have your numerator and denominator terms, and your solution should be obvious. Hopefully that was somewhat clear and helpful.
Try this
import java.io.IOException;
public class StandardDeviationCalc {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
double [] values = {9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10,
9, 6, 9, 4 }; //change input values here
double sum=0;
double finalsum = 0;
double average = 0;
for( double i : values) {
finalsum = (sum += i);
}
average = finalsum/(values.length);
System.out.println("Average: "+ average);
double sumX=0;
double finalsumX=0;
double[] x1_average = new double[2000];
for (int i = 0; i<values.length; i++){
double fvalue = (Math.pow((values[i] - average), 2));
x1_average[i]= fvalue;
System.out.println("test: "+ fvalue);
}
for(double i : x1_average) {
finalsumX = (sumX += i);
}
Double AverageX = finalsumX/(values.length);
System.out.println("E(X1-x1_average)^2/AverageX: "+ AverageX);
double SquareRoot = Math.sqrt(AverageX);
System.out.println("Standard Deviation: "+ SquareRoot);
}
}
You can tweak to how u want like adding user input.The code is rough becose I assume this is a homework. try to make it nice in your own way. hope it helps you.
What have you tried?...
You will need to loop the values for example to print all the values
for(int i = 0; i < yourArray.length; i++)
{
System.out.println(yourArray[i]);
// Add your code to calculate the values you need for standard dev
}