简体   繁体   中英

Finding the smallest number in array list java

So I have some code which is finding the distance between a series of points. One method uses the euclidean distance and is working fine, the other is using Manhattan and I don't know why it isn't working.

I have it set up so that the distance of the first element in the array list is zero for both methods, and therefore should print that image 1 is a match. However the Manhattan method always returns image 31, no matter how many different elements I test it with. I have double checked the elements in the array list and it should be returning image 1.

Does anybody have any ideas? Thanks in advance

public void matchEuclidean(){
    for(int i = 0; i < numberimages; i++){
        distanceE[i][0] = weights[i][0] - testweights[0][0];
        distanceE[i][1] = weights[i][1] - testweights[0][1];
      }
      
    for(int i = 0; i < numberimages; i++){
        distanceEu[i] = (Math.pow(distanceE[i][0], 2)) + (Math.pow(distanceE[i][1], 2));
        distanceEu[i] = Math.sqrt(distanceEu[i]);
       }  
       
     
for (double no : distanceEu) {
     list.add(Double.valueOf(no));
     }
      
   double max= Collections.min(list);
   double min =  list.indexOf(max) + 1;    
 System.out.println("(euclidean) the unknown image matches image " + (min)); 


 }
 
 public void matchManhattan(){
     for(int i = 0; i < numberimages; i++){
        distanceM[i][0] = weights[i][0] - testweights[0][0];
        distanceM[i][1] = weights[i][1] - testweights[0][1];
      }
      
      for(int i = 0; i < numberimages; i++){
        distanceMu[i] = distanceM[i][0] + distanceM[i][1];
        
       } 
  
     for (double no : distanceMu) {
     listM.add(Double.valueOf(no));
     }
      
     double max= Collections.min(listM);
     double min =  listM.indexOf(max) + 1;    
     System.out.println("(Manhattan) the unknown image matches image " + (min)); 


 }

It looks like you neglected to use the Math.abs function in Manhattan distance :

distanceMu[i] = Math.abs(distanceM[i][0]) + Math.abs(distanceM[i][1]);

Without it, you don't really have a valid "distance" function: you can get negative values, and the triangle inequality does not hold

int a[] = {6,22,33,12,44,9};

    int low = 0;
    
    for(int i = 1 ; i < a.length ; i ++ )

    {
        if(a[0] < a[i])
        {
            low = a[0];
        }
        else if(a[0] > a[i])
        {
            low = a[i];
            a[0] = low;
            
        }
    }
    System.out.println("The smallest number is the given array is : " + low);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM