I am using a .DAT file that contains 700 x and y coordinates with a name of the location, I know how to separate the x and the y for each of them, so at the moment each coordinate is separated. So my main point is set up like USAcamp 50 50 and I need to find the farthest distance away from 50,50 inside my code with the name attached. What is the best formula to use to find this? I also need to find how many miles are between each point and 50,50.
Everything is seperated like this:
string usaNames;
double x;
double y;
Thanks for any help, I can clarify on things if this is too confusing, I'm learning so everything helps.
Shortest distance between two points is:
SQRT((x2-x1)^2 + (y2-y1)^2)
Thus do this calculation for all sets of points and find the greatest distance.
As it related to C#, I would create a composite class around C#'s Point class and add the field for the name, then perform the nested for-loop to find the distances.
double max = -1;
for(int i = 0; i<arr.length-1;i++){
for(int j = i+1; j<arr.length; j++){
// Calculate the distance and set the max if highest
}
}
For more information look at this post: What is the most efficient way to calculate the maximum distance of two points in a list?
Related
i have a 2d array of tuples representing the xy coordinates of equally spaced points. what i need to do is given a center point coordinates, get all other points within radius. i have found this picture on the internet which sort of demonstrate what i want to achieve only difference is that my array is not random.
i have been using a kdTree to search for items within radius and it works fine but for a lot of points this gets super slow. i have also tried the following but it is also extremely slow
for (int i = 1; i < radius; i++)
{
for (int j = 1; j < radius; j++)
{
if (i*i + j*j <squaredRadius)
{
points.Add(new int[]{i,j});
points.Add(new int[]{-i,j});
points.Add(new int[]{i,-j});
points.Add(new int[]{-i,-j});
}
}
}
i was if anyone would have any suggestions on a faster way to achieve this
I think you can you a formula like (x-a)^2 + (y-b)^2 = r^2 where (a,b) is coord of the center and r is its radius. Then use (x-a)^2 + (y-b)^2<=r^2 to check if (x,y) is with the radius or not.
You can loop all the cell of your array to collect all the value you need or you can use some math to narrow the range of x and y to make the finding process faster.
This problem lends itself perfectly for parallel execution. You need to find the boundary of one quadrant then you can spawn 2r threads and do this for each vertical strip or horizontal strip (like a blur image filter). That should speed things up.
Obviously you will have to bounds check in each thread, think if your center point is corner or edge or close to....
As the title suggests, I am trying to generate a coordinate based on another coordinate that is within an x mile (or whichever unit is most convenient) radius of the inputted one.
As an example:
I am given a geographic coordinate (lat, lon) of 39.083056, -94.820200.
I want to be returned another set of coordinates that is within a x
miles radius of that coordinate, such as 39.110998, -94.799668.
The x mile radius isn't as important as the fact that the returned
coordinates are within that x mile radius.
I have searched and searched, but I must be searching the wrong thing because all the posts that I have been able to find seem like they get very close to what I am trying to do but aren't quite hitting the nail on the head.
I'm sorry you're being downvoted to oblivion. I understand it can be frustrating trying to search for something without knowing what exactly to search for.
You may be interested in Orthodromic Lines/Distances: wiki. If this answer doesn't fulfil your needs, at least you have a new term to google and hopefully will lead you to one that does suit.
You could try using the Geo library. Its documentation is on the sparse side, but it does contain a method that could be useful to you: CalculateOrthodromicLine(startPoint, heading, distance)
A pseudocode would be something as simple as this:
var startPoint = new Coordinate(lat, long);
var heading = Random between 0 and 360 degrees
var distance = Random between 0 and X metres
var endPoint = //<-- et voila!
GeoContext.Current.GeodeticCalculator
.CalculateOrthodromicLine(startPoint, heading, distance)
.Coordinate2;
Edit: As mentioned in the wiki, the Earth is not a perfect sphere, but a spheroid instead. The library's GeoContext.Current by default uses its Spheroid calculations, so you should be okay.
Good luck!
I am practicing my programming skill using Unity3D. I have a grid set up that has coordinates in an x,y type of setup.
[0,0] to [10,10]
With all the numbers in between (I.E. 5,5 would be close to center of the map).
The thing that I am trying to do now is figure out a mathematical formula to calculate the coordinates my character can move. If the character is at position 5,5 and has a movement radius of 2 what is the most efficient way to return a list or an array of coordinates my character can move to? Every single grid square is its own object and have public variables for its X and Y so once I have the available results actually using them in the code isn't hard.
Here's what I'm trying so far (I'm ignoring the out of range possibility for right now, that's an easy fix):
for(int x = currentGridSquare.xCoord - myMovementRange;
x <= currentGridSquare.xCoord + myMovementRange; x++){
for(int y = currentGridSquare.yCoord - myMovementRange;
y <= currentGridSquare + myMovementRange; y++)
{
//Starting at 5,5 with a movement range of 2 should
//start this process at the value of 3,3 which
// is incorrect
}
}
I may be too tired to actually calculate a formula for this but I've been searching and haven't come across anything so if anyone's had experience with this and knows a quick way to do it I would be greatly appreciative.
Update: The values that I am expecting this to return would be coordinates. In this example starting at 5,5, the values I'd want back would be [3,5],[4,4],[4,5],[4,6],[3,5],[4,5],[5,5],[6,5],[4,6],[5,6],[6,6] and [5,7]
So I used formula Ben provided and came up with:
foreach(var gridSquare in allGridSquares)
{
if( (Mathf.Abs(myX - gridSquare.Xcoord) + (Mathf.Abs(myY - gridSquare.Ycoor) >= myMovementValue)
{
gridSquare.activate();
}
}
I know that if the grid starts getting bigger than the distance formula will be more complicated and I will update this later if that's the case but for the size of my grid this works wonderfully.
public void checkForCollision () {
int headX = cells[0].x;
int headY = cells[0].y;
int noOfParts = nPoints;
for(int i = 1; i <noOfParts;i++)
{
int tempX = cells[i].x;
int tempY = cells[i].y;
if(tempX == headX && tempY == headY){
JOptionPane.showMessageDialog(null,"Head hit body");
//EndGameCollectScore etc.
}
}
}
EDIT: 'Cells[]' is an array of type Point AND noOfParts is just how many segments the snake has
main Question
With the above code I'm trying to compare tempX to headX but i would like to have a sort of margin for error e.g. +-5 but am unsure how to accomplish this, my reasoning behind this is i'm thinking maybe the x and Y variables might be a few digits apart so if i have the radius of one of the segment of the snake (explanation of 'snake' in Alternate below) then if i'm right and the values are a tiny bit off it should still come back positive.
OR
Alternative
if anyone can suggest a better way for doing this? Basically it's for a Snake game and headX and headY is the head of the snake and the remaining X and Y variables in Cells is the body, and I'm attempting to compare if the head hits the body.
I tested it and it seemed to work but after i tested it again it seems it will only pick up the collision if i make the snake double back on itself for a few squares. e.g. IF i cross the body perpendicular it will not detect the collision.
Also i am fairly certain that this method is called after each block the snake moves.
Cheers,
Shane.
P.S Running of very little sleep and way too much sugar in my blood, If you need further clarification because the above doesn't make alot of sense let me know.
int eps = 5;
if (Math.abs(tempX - headX) <= eps && Math.abs(tempY - headY) <= eps) {
// ...
}
To check if two points are within a delta from each other, compute the distance between them. You can avoid going into the square root territory by using squares, like this:
int distSq = (tempX-headX)*(tempX-headX) + (tempY-headY)*(tempY-headY);
int minDist = 5;
if (distSq < minDist*minDist) {
// too close
}
I don't know how your snake looks, but if it has a complex shape, looking for a hit can be expensive in terms of speed. You can speed up collision detection if you can do a quick test, to see if a collision is possible at all. You can do this by using a bounding box. You would have to keep track of minimum and maximum x and y positions of the snake body. Only if a coordinate lies within these boundaries you would take account of the exact shape of the snake. How this has to be done depends on how the snake is represented. Check for each tile or each pixel the snake is made of or possibly check if the coordinate is within a polygon, if the snake outline is defined by a polygon. (I'm not going to explain how this works here, but you will find algorithms if you google a bit.)
If you need to calculate the distance to another point (the snake head), you can use different metrics for this. If only horizontal and vertical movements are possible within the game, the so called Manhattan or taxi distance can be used: d = |x1-x0| + |y1-y0|. It consists of adding the x and y distances, or you can use the maximum of both distances: d = Max(|x1-x0|, |y1-y0|) (correponds to 2kay's approach).
If you need the exact distance, apply the Pythagorean formula. In order to compare the distance with the error margin, you don't need to calculate the square root. Instead compare the square of the distance with the square of the error margin. This saves time. (x1-x0)^2 + (y1-y0)^2 < error_margin^2.
I have an application (cad like editor) in which the user may place a lot of positional nodes (defined by their latitude and longitude). The application needs to tell the user if these nodes are very close together - a common design error is to overlap them. What the app is doing is something rather like ReSharper or CodeRush does in the IDE - parses the project and reports problems. A project may have several thousand of these nodes so testing for overlap becomes exponetially more time consuming as the numbers go. At the moment I am using two for loops to get through the list.
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
// check the distance between the i and j elements and if less than
// a predetermined value report it
}
}
I would like to get the process of identifying these into 'real time' so that the user is told at once in the event that an overlap occurs. The looping is expensive as is the testing of the distance between nodes. Most of the comparisons are wasted of course.
I just wonder if there is another way. I have thought about sorting the list by lat and lon and comparing adjacent elements but I suspect that will not work nor necessarily be faster.
My other thought is to move the activity to another thread (I really have no experience of using multiple threads) so that the values are being updated - for example storing a reference to nearby nodes in each object. However I can imagine needing to clone the object tree for the background thread so that there is no conflict with the foreground.
You could look into Tessealtion.
Executing this on another Thread is a completely separate issue, you could do that with your nested loops as well as with a more efficient algorithm.
Since the user is placing these locations, the ideal solution would be to assume all previously placed points are not nearby, and with each new point or moved point, check against the rest -- this becomes a single for loop, which should be reasonable.
Another, more ideal solution however:
Let position of A be lat, lng.
Convert both lat and lng to a fixed-length representation
(truncating the degree of precision to a value below which
you are sure they will overlap)
Let xa = lat . lng (concatenate both)
Let ya = lng . lat
Given some position B, find xb, yb.
B is 'close' to A iff | xa - xb | < delta, | ya - yb | < delta.
So what you can do is sort the values of xi, yi for all your input points. When you want to check for points that are too close, you need to traverse through the list of xi's to find points that are too close together (linear time, since they will be adjacent) and then check if the same points in the list of yi's are too close.
Thanks to the insights given here I think I have found a reasonable way to deal with this.
*First to sort all the points in latitude order.
*Then loop through the sorted list.
*For each entry in the list compare the latitude offset (distance in meters) to the entries below it.
*If the latitude offset is less than the test distance then check the actual distance from point to point and if it is inside the test radius report the issue.
*When the latitude offset exceeds the test distance move on to the next point in the list and repeat the tests.
I have not written the code yet but it seems to me that if there are no overlaps then I will make a single pass. Since overlaps are rare in practice then the total number of tests is likely to be quite small. For 1000 points the current method makes 500,000 tests. The new method is unlikely to make more than a few thousand.