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];
}
}
Related
How can I optimize my algorithm to find the minimum absolute value difference in a given array. Here is my approach which checks each and every element and returning the value.
static int minAbsVal(int[] myArray){
ArrayList<Integer> diffs= new ArrayList(); // all absolute value differences
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray.length; j++) {
if (myArray[j]!=myArray[i]){
int absVal =Math.abs( myArray[i]- myArray[j]);
diffs.add(absVal);
}
}
}
int min = diffs.get(0);
for (int i = 1; i < diffs.size(); i++) {
if (min>diffs.get(i)){
min = diffs.get(i);
}
}
return min;
}
Check this solution. If array contains duplicates than it returns 0 if you wanna avoid than you can add conditions also.
static int minAbsVal(int[] myArray){
Arrays.sort(myArray);
ArrayList<Integer> diffs= new ArrayList<Integer>(); // all absolute value differences
for (int i = 0; i < myArray.length-1; i++) {
diffs.add(Math.abs( myArray[i+1] - myArray[i]));
}
Collections.sort(diffs);
return diffs.get(0);
}
Or you can also use :-
static int minAbsVal(int[] myArray){
Arrays.sort(myArray);
int minimum=Math.abs( myArray[1] - myArray[0]);
for (int i = 1; i < myArray.length-1; i++) {
int diff = Math.abs( myArray[i+1] - myArray[i]);
if (diff == 0)
return 0;
else if (minimum > diff)
minimum = diff;
}
return minimum;
}
Check the following solution,
static int minimumAbsoluteDifference(int n, int[] arr) {
int a = Math.abs(arr[1]-arr[0]);
Arrays.sort(arr);
for(int x=0;x<n-1;x++){
if(Math.abs(arr[x]-arr[x+1])<a){
a = Math.abs(arr[x]-arr[x+1]);
if(a==0){
return a;
}
}
}
return a;
}
Dependson the size of your array a good approach would be to divide it in different smaller arrays and look for the minimum of each in pararell and then compare those results .
Anyways you dont need so many iterations, you can just set the baseValue to the first element of the array and when iterating the array compare the baseValue vs the current, if the current is smaller then asign baseValue to current (I would rename baseValue to minValue in that case)
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.
I want the method to count all the maximum/minimum values in the 2D array poängInsamling. Each domare (=judge) gives a value to all deltagare (=members). I want to remove the maximum/minimum value of each deltagare. The code I have now only works if there are 2 or less members.
This is what I got:
for (int x = 0; x < deltagare; x++) {
for (int y = 0; y < domare; y++) {
if (poängInsamling[y][x] == -1) {
poängInsamling[y][x] = 0;
break;
}
}
}
return poängInsamling;
}
Thanks in advance, I've been trying to fix this for hours.
Edit: int[][]PoängInsamling = int[domare][deltagare];
If all deltagare has the same value, all their points end up 0.
You are searching the entire 2D array in order to remove the lowest and highest value across all members, but you want to remove the lowest and highest value only for the current member. You can eliminate the second loop if you keep track of the index having the maximum/minimum value.
For example, for the maximum (the minimum will be similar) :
int max = -1;
int maxIndex = -1;
for(int i = 0; i < deltagare; i++) {
max = -1; // clear the max value when starting with a new member
maxIndex = -1;
for(int t = 0; t < domare; t++) {
if (poängInsamling[t][i] > max) {
max = poängInsamling[t][i];
maxIndex = t;
}
}
// clear the max value for the current member
poängInsamling[maxIndex][i] = -1;
}
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.
i have an array of integer arrays 'int pixels[][]'
and i want to find the sum of all of them so i can find the average pixel value
this will be used so that i can set the average value of a pixel to be the threshold value for a pbm image
if the value if above threshold i will export a white pixel if its below i will export a black one (just to give some context)
i assume the code below is not correct at all as the output it 6.0 but i think its something like this
double threshold = 0;
for(int i = 0; i < pixels.length; i++)
{
threshold += (double)pixels[i][i];
}
System.out.print(threshold);
Do you want to iterate all number in arrays,you can try with this:
double threshold = 0;
for(int i = 0; i < pixels.length; i++)
{
for(int j=0;j<pixels[i].length;j++){
threshold += (double)pixels[i][j];
}
}
System.out.print(threshold);
HINT
You have a 2D array, So to add each element you need to traverse each column of each row. For this 2 for loops might be of some use.
traverse over each value and add them
exit loop
Divide your sum with number of elements to get average (you may need to give some thought to type casting here)
You need to iterate over each row and column in the array, so you need 2 for-loops. What you're currently doing only covers the following: (0,0), (1,1), (2,2), ....
This would work: (assuming a non-jagged array, at least for the threshold calculation)
long sum = 0;
for (int i = 0; i < pixels.length; i++)
for (int j = 0; j < pixels[i].length; j++)
{
sum += pixels[i][j];
}
double threshold = (double)sum / (pixels.length * pixels[0].length);
System.out.print(threshold);
Or more simply: (assuming a non-jagged array, at least for the threshold calculation)
long sum = 0;
for (int[] i: pixels)
for (int j: i)
{
sum += j;
}
double threshold = (double)sum / (pixels.length * pixels[0].length);
System.out.print(threshold);
You need to use a double for here. Something like this:-
for(int i = 0; i < pixels.length; i++){
for(int i = 0; i < pixels[i].length; i++){
threshold += (double)pixels[i][j];
}
}
you dont need a double when you count sum of ints, this is a waste, use long, it's faster
long sum = 0;
int n = 0;
for (int[] a : pixels) {
for (int e : a) {
sum += e;
n++;
}
}
double avg = ((double) sum) / n;