So currently I have the following which finds me the shortest/nearest neighbor by taking the smallest distance value from my "distance" array which has the calculated distances. Then it does another search to track down it's index which then indicates to me which patient it belongs to.
However say I wanted to find the 3 nearest neighbors, how would I do that? Do I need to change my code entirely to accommodate for this?
Many thanks
int min = 99;
int d = 1;
String diagnosis;
//Finding smallest value from an array containing distance to new 'patient'
for(d=1; d<= numberOFinstances; d++){
if(distance[d] < min)
min = distance[d];
}
for (int p = 1; p < numberOFinstances; p++)
{
if (distance[p] == min){
System.out.println("Nearest patient to new patient is Patient "+p+ " with a distance of: " + min);
//Here I'm saying 6 because the diagnosis is in column 6 within the matrix
diagnosis = data[p][6];
System.out.println("The new patient's diagnosis is: " + diagnosis);
}
}
Best way to accomplish would be to use Arrays.sort(int[])
Arrays.sort(distance);
int[] toReturn = new int[k];
for (int i = 0; i < k; i++) {
toReturn[i] = distance[i];
}
Related
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 = a[0];
for(int i = 1 ; i < a.length ; i ++ )
{
if(a[i] < low)
{
low = a[i];
}
}
System.out.println("The smallest number is the given array is : " + low);
}
}
I am trying to calculate the euclidean distance between 2 values in a 2d array. I need the largest, so I have 2 for loops to travers the arrays, and I also have a maxDistance variable to store the greatest distance as I compare.
My code looks like this
//Returns the largest Euclidean distance between any two cities
within the cities array
public static double furthestDistance(int[][] x)
{
int power;
double sum = 0.0;
int distance = 0;
int maxDistance = 0;
for (int i = 0; i < x.length; i++)
{
for(int j = 0; j<x[0].length; j++)
{
sum = (x[i][j] - x[i][i+1]) + (x[i][j] - x[i][j+1]);
power = (int) Math.pow(sum, 2);
distance = (int)Math.sqrt(power);
if (distance > maxDistance)
{
maxDistance = distance;
}
}
}
return Math.sqrt(sum);
}
I am having issues, getting an error that says my arrayIndex is out of bounds, but I am not sure what the ebst way to travers my array to find the largest distance between any two values in my 2d array of around 10 "x,y coordinates"
x is an array of cities which looks like this
int[][] cities0 = {{22,-45},{-20,-43},{-45,29},{41,35},{21,4},
{23,-37},{16,-19},{-44,-10},{26,15},{6,-30},{2,35},{6,-19}};
I am not sure if I am approaching the problem the right way of if I am even calculating the distance properly?
The Euclidean distance is
public static double calculateDistance(int[] array1, int[] array2)
{
double Sum = 0.0;
for(int i=0;i<array1.length;i++) {
Sum = Sum + Math.pow((array1[i]-array2[i]),2.0);
}
return Math.sqrt(Sum);
}
Now, the thing is that you have an array of points, each point is represented by a two-element array. The index out of bounds error stems from the fact that you have the line of
sum = (x[i][j] - x[i][i+1]) + (x[i][j] - x[i][j+1]);
which assumes that there is a next i and a next j, also, it assumes that the i'th element of x has at least i + 2 elements, which, if i > 0 will crash. Using the method I described at the start of my answer, your solution would look like:
double maxDistance = -1;
int firstPoint = -1;
int secondPoint = -1;
//notice that the limit is x.length - 1, because we will compare the penultimate
//item with the last
for (int i = 0; i < x.length - 1; i++) {
for (int j = i + 1; j < x.length; j ++) {
double d = calculateDistance(x[i], x[j]);
if (d > maxDistance) {
maxDistance = d;
firstPoint = i;
secondPoint = j;
}
}
}
Your Euclidean distance calculation was wrong in the initial code.
Also, the statement x[i][i+1] is problematic because you have tuples as data points and each tuple is in a different row, which means that the
elements in the array can be accessible by either x[i][0]or x[i][1] and any value greater than 1 in the second bracket will cause an IndexOutOfBounds Error.
Modifying the inner loop of the code can help you :
for(int j = i + 1; j<x.length; j++)
{
sum = Math.pow((x[i][0] - x[j][0]), 2) + Math.pow((x[i][1] - x[j][1]), 2);
distance = Math.sqrt(sum);
System.out.println(distance);
if (distance > maxDistance)
{
maxDistance = distance;
}
}
Since we have tuples as our coordinates, x[i][0] - x[j][0] denotes the difference between x-coordinates of the two points and x[i][1] - x[j][1] denotes the difference between y-coordinates. Using that notation, we calculate Euclidean distance. The rest is what you have wrote previously. Also change the variables to double rather than int for more precision in your calculations!
Note: This example is hard-coded for the input you gave in your question, you might need to modify it for using with different arrays.
I started writing some code today to test some different solutions to the traveling salesman problem. I have run some tests for the random algorithm and the nearest neighbor algorithm, however, I am struggling with the brute force method.
What my program does is ask the user how many cities they will add. It then asks them to input the cities name followed by their longitude and latitude. I have created a method to then generate a 2-dimensional array in which the distances between all cities are stored.
What I want my brute force algorithm to do is calculate the distance between all combinations of cities and at the end output the shortest distance.
For example:
3 cities are entered(New York, Paris, Shanghai)
The distances between them is then stored.
[0.0, 5834.0, 11851.0]
[5834.0, 0.0, 9257.0]
[11851.0, 9257.0, 0.0]
Now I want to work out all the possible combinations and their total distance:
NY-P-S-NY
NY-S-P-NY
P-NY-S-P
P-S-NY-P
S-NY-P-S
S-P-NY-S
My issue is avoiding the 0.0 distances from the array, which will obviously result in shorter routes.
Any help is much appreciated. Please note I am only just learning to code so if possible I prefer less efficient and easier to understand answers :)
The code below is my attempt of getting it to work for 4 cities, however, I wish for the program to be able to complete this task for any amount of cities. I am well aware what I tried is unsuccessful:
int numCities = weights.length();
List<Integer> brute = new ArrayList<Integer>();
for (int i = 0; i< 4; i++){
brute.add(i);
}
System.out.println(brute);
double weight = 0.0;
double tempWeight = 0.0;
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;
int temp4 = 0;
int removing = 0;
int valuetoRemove = 0;
for (int a = 0; a < 4; a++){
for (int b = 0; b < 3; b++){
temp2 = brute.get(b);
//System.out.println(temp2);
List<Integer> brute2 = new ArrayList<Integer>();
brute2.addAll(brute);
brute.remove(b);
System.out.println(brute);
for (int c = 0; c < 2; c++){
temp3 = brute.get(c);
//System.out.println(temp3);
List<Integer> brute2 = new ArrayList<Integer>();
brute2.addAll(brute);
brute.remove(c);
//System.out.println(brute);
temp4 = brute.get(0);
//System.out.println(temp4);
//brute.remove(0);
//System.out.println(brute);
tempWeight = weights[temp1][temp2] + weights[temp2][temp3] + weights[temp3][temp4] + weights[temp4][temp1];
System.out.println(tempWeight);
brute = brute2;
}
}
}
I have 2D array of type doubles as spectral data in text file. I have to find peaks in the spectrum. I am using Binary Search to find peaks in the array, but I am getting false peaks also. How can I filter the result I am getting. If anybody know about this please help me
Here is the code which I am using
static ArrayList < Double > nPeaks(double[] array, int range) {
if (array == null) {
System.out.println("Error");
}
double result = 0, l, r;
double[] peaks = null;
// Check main body
for (int i = 0; i < array.length; i++) {
boolean isPeak = true;
// Check from left to right
l = Math.max(0, i - range);
r = Math.min(array.length - 1, i + range);
for (int j = (int) l; j <= r; j++) {
// Skip if we are on current
if (i == j) {
continue;
}
if (array[i] < array[j]) {
isPeak = false;
break;
}
}
if (isPeak) {
//System.out.println("Peak at " + i + " = " + array[i]);
peaklist.add(array[i]);
result++;
i += range;
}
}
return peaklist;
}
Your question is not clear to me. I assume you are generating the max to min order of input array. If yes, you are trying to create a sorted array(descending order).
Simply sort the array in descending order. That will have result like
peak1, peak2, peak3...peakn
where,
peak1 - is max value
peakn - is min value
One of the way to find peaks in spectrum is calculating the disspersion of whole spectrum and then devile it by 3*sigma and take floor funstion. After it you shold "see" only peaks and each place higher than 1 shold be a peak
Hey guys I'm really struggling with trying to print my array index and element value, I posted a question a few days ago and got really helpful advice but cannot seem to get this part right at all, I am able to print the 1st index of the array (distance) but not able to print the entire thing without losing the original index value:
double minVal = Double.MAX_VALUE;
int minIndex = -1;
for (int i=0, max=distances.length; i<max;i++) {
if (distances[i] < minVal) {
minVal = distances[i];
minIndex = i;
//Gets the minimum point and minimum distance
}
}
System.out.println("The Nearest to point K is point: "+minIndex+" with distance "+minVal);
Really sorry to keep bringing this matter up but really have tried and cannot get it to work for the life of me any help or advice would be appreciated.
First, you sort
for (int i=0; i<distances.length; i++) {
for(int j = i+1; j<distances.length; j++)
{
if (distances[i] > distances[j])
{
double temp = distances[j];
distances[j] = distances[i];
distances[i] = temp;
}
}
}
Then, you merely print
for (int i=0; i<distances.length; i++) {
System.out.println(i + " -> " + distances[i]);
}
If you want to keep the original indexes, you can do that too.
the most obvious way would be to have a second paralell array, and sort that along with your original array
example:
if (distances[i] < minVal)
{
double temp = distances[j];
int tempindex = indices[j];
...
the better way would be to make a class with an index(or more appropriately named, an ID), and a value(which is your double), and sort an array of type Distance.
.
Class Distance
{
public int ID;
public double value;
}
Try change the for loop to for(int i=0; max = distances.length && i < max; i++){...}