Get the minimum value and its index with a for loop - java

How can I get the minimum value in a for loop plus its index:?
Update: This is what I tried after using #Sakalya 's answer
LatLng myLatLang = new LatLng(myLocation.getLatitude(),myLocation.getLongitude());
double minval = -1.0;
int minIndex = 0;
for (int i = 0; i < stationsCoord.size(); i++) {
double distance = CalculationByDistance(myLatLang,stationsCoord.get(i));
if(distance < minval){
minval = distance;
minIndex = i;
}
Log.i("distance " , String.valueOf(distance));
System.out.println("min=" +minval+ "index="+minIndex);
}
//i'm looking for the min value of 'distance' + the index 'i'
I always get this: System.out: min=-1.0index=0
Thank you in advance.

First you can set a min variable to 1000000 and then iterate the list to find min value as below:
LatLng myLatLang = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
double minval = 1000000000000.0;
int minIndex = 0;
for (int i = 0; i < stationsCoord.size(); i++) {
double distance = CalculationByDistance(myLatLang,stationsCoord.get(i));
if (distance < minval) {
minval = distance;
minIndex = i;
}
Log.i("distance " , String.valueOf(distance));
System.out.println("min=" +minval+ "index="+minIndex);
}

In the following code
double minval = -1.0;
if (somepositivedistance < minval ) { // do something
}
nothing will ever return true if the distance is positive, therefore the statement will never execute.
You need to set minvalto something greater then the largest possible distance (for example Double.MAX_VALUE) before entering the for-loop.

Related

Getting the second lowest value in an array using only loops while already having the lowest value

I am trying to figure out on how to get the second lowest value from an array that is input by the user.
To get the lowest value I've done this:
int min = Integer.MAX_VALUE;
for(int i = 0; i<array.length; i++) {
if( array[i] < min ) {
min = array[i];
}
}
To get the second lowest value I have tried this
int secMin = 0;
for(int i = 0; i<array.length-1; i++) {
if(array[i+1] > array[i]) {
secMin = array[i];
}
}
The output is not consistent, meaning sometimes its right sometimes it isn't.I've tried changing the loop as well as the statements but its just guess work and I'm not making any real progress. Any tips?
If you want to keeping doing it as 2 separate loops, just do the same as for the min value, but skip the min value when looking.
// Find lowest value
int min = Integer.MAX_VALUE;
for (int value : array) {
if (value < min) {
min = value;
}
}
// Find second-lowest value
int secMin = Integer.MAX_VALUE;
for (int value : array) {
if (value != min) { // Skip/ignore lowest value
if (value < secMin) {
secMin = value;
}
}
}
You can of course combine that:
// Find second-lowest value
int secMin = Integer.MAX_VALUE;
for (int value : array)
if (value != min && value < secMin)
secMin = value;
You could simply update your first loop to look for both min and secMin at the same time. Try this:
int min = Integer.MAX_VALUE;
int secmin = Integer.MAX_VALUE;
for(int i = 0; i<array.length; i++) {
if( array[i] < min ) {
secmin = min; // the min is now second min
min = array[i]; // the curent value becomes min
} else if ( array[i] < secmin ){
// if the value is greater than min but still less than second min then...
secmin = array[i];
}
}
I haven't tested it but something along those lines should work
There's another approach described here.

Creating array from range of numbers

I need to create an array of doubles given a max and min and interval. So array will look something like {2.9, 4.9, 6.9,... etc}
I am getting an array of zeros.
public class FoolinAround {
public static void main(String[] args) {
double min = 2.9;
double max = 20.6;
double gap = 2.0;
double count = (max - min) / gap + 2; // as will need first and last
// element also
double array[] = new double[(int) count];
for (int j = 0; j < array.length; j++) {
double i = array[j];
min = min + gap;
}
for (double k : array) {
System.out.print(array[(int) k] + ",");
}
}
}
It appears you are missing the assignment to your array (array[j] = something;). It appears from your explantation that array is supposed to contain the results. If I understand the problem you are trying to solve, this looks like a solution.
public class FoolinAround {
public static void main(String[] args) {
double min = 2.9;
double max = 20.6;
double gap = 2.5;
double count = (max - min) / gap + 2; // as will need first and last
// element also
double array[] = new double[(int) count];
for (int j = 0; j < array.length; j++) {
array[j] = min + (j*gap);
}
for (double k : array) {
System.out.print(array[(int) k] + ",");
}
}
}
I didn't verify that this calculation will give you the correct size for your array: double count = (max - min) / gap + 2;. I suggest that you verify this calculation. Since you are relying on truncation, rather than rounding, you may have an off-by-one error.
Here is how
double[] array = DoubleStream.iterate(min, prev -> prev + gap)
.limit(count)
.toArray();
Link to DoubleStream
The problem that I found was with the assignment and the for-each loop. Here is how you can do it:
double min = 2.9;
double max = 20.6;
double gap = 2.0;
double count = (max - min) / gap + 2.0;
System.out.println(count);
double array[] = new double[(int) count];
for (int j = 0; j < array.length; j++) {
// double i = array[j]; /*Not sure why this assignment is used
// here?*/
array[j] = min;
min += gap;
}
for (double k : array) {
System.out.print(k + "\n"); // Here k is the double value from the
// array. array[(int)k] will give you
// element of array indexed at the
// element of array.
}

Find min in Arraylist of object, can't compare the elements in an arraylist

I'm trying to invoke the getScore() method in my StudentScore class to determine the min and max over elements in an ArrayList, within the printStat() method presented below. I'm getting an ArrayIndexOutOfBoundException. What does that mean, and how can I fix the problem?
public class ScoreCalculator{
private int[] scoreCounter;
ArrayList<StudentScore> scores ;
public ScoreCalculator(int maxScore) {
scoreCounter = new int[maxScore];
scores = new ArrayList<StudentScore>(maxScore);
}
public void printStat() {
System.out.println("Score Report for " + scores.size() + " Students ");
min = 0;
max = 0;
int j=0;
for ( j = 0; j < scores.size(); j++) {
if (scores.get(j).getScore() < scores.get(j - 1).getScore()) {
min = scores.get(j).getScore();
}
if (scores.get(j).getScore() > scores.get(j - 1).getScore()) {
max = scores.get(j).getScore();
}
}
System.out.println(min);
System.out.println(max);
}
If your loop starts form j=0, and you access the element at j-1 in the list, you will see where the issue is.
When j=0, you try to access -1. There is no index -1. Hence the error. Starting from j=1 solves this.
Does this help in any way?
please,
change from
for(j=0;j<scores.size();j++){
to
for(j=1;j<scores.size();j++){
You cannot find the min/max of a sequence by only comparing neighboring values.
You have to compare values to the min/max-so-far.
if (scores.isEmpty())
throw new IllegalStateException("No scores found");
int min = scores.get(0).getScore();
int max = min;
for (int j = 1; j < scores.size(); j++) {
int score = scores.get(j).getScore();
if (score < min)
min = score;
if (score > max)
max = score;
}

Find biggest value in Java

For an input like the following is it ok to use Float.compare to find the biggest float in an array?
Float[] v = {0.38118651972530804, 0.3580139606405057, 0.7358862700995704};
float max = -1;
for (int i = 0; i < v.length; i++)
if (Float.compare(max,v[i]) > 0) max = v[i];
Is there a better way? or maybe there could be some precision error?
I'd use a collection and call the max() method. See: here
How about one line:
Float max = Collections.max(Arrays.asList(v));
There can be errors if all the values in the array are less than -1. Better to initialize max as v[0].
And, your code finds the smallest element. Not the largest element.
Float[] v = {0.38118651972530804, 0.3580139606405057, 0.7358862700995704};
float max = v[0];
for (int i = 1; i < v.length; i++)
if (Float.compare(max, v[i]) < 0) max = v[i];
How about this-
float max = v[0]; // the first item in array
// Loop through all items starting the second one
for (int i = 1; i < v.length; i++)
{
if (v[i] > max) // If current item is bigger, update max to current item
{
max = v[i];
}
}

Mathematical notation to programming code

I have difficulties with transcripting the following two functions written in mathematical notation into Java code (the input of both functions is an array with D elements):
Can somebody take a look at the code below and tell me if something is wrong with it?
public double firstFunction(double[] arrayOfElements) {
double sum = 0;
double sumTwo = 0;
for(int i = 0; i < arrayOfElements.length; i++) {
for(int j = 0; j < i; j++){
sumTwo = sumTwo + arrayOfElements[j];
}
sum = sum + Math.pow(sumTwo, 2);
}
return sum;
}
public double secondFunction(double[] arrayOfElements) {
double maximum = Math.abs(arrayOfElements[0]);
for (int i = 0; i < arrayOfElements.length; i++) {
if (Math.abs(arrayOfElements[i]) > maximum) {
maximum = Math.abs(arrayOfElements[i]);
}
}
return maximum;
}
The first method should reset sumTwo to zero in every iteration. Currently it accumulates values from one execution of the outer loop to the next. Otherwise it's OK.
Alternatively, and more efficiently, you could notice that the difference between the sumTwo of one iteration and the next is the new array element. This means you don't need the inner loop.
for(int i = 0; i < arrayOfElements.length; i++) {
sumTwo = sumTwo + arrayOfElements[j];
sum = sum + Math.pow(sumTwo, 2);
}
The second method is supposed to return the index of the element with maximum absolute value, not the element itself. Note the subindex i in max.

Categories

Resources