calculating shortest grid distance - java
Consider a city where the streets are perfectly laid out to form an infinite square grid. In this city finding the shortest path between two given points (an origin and a destination) is much easier than in other more complex cities. As a new Uber developer, you are tasked to create an algorithm that does this calculation.
Given user's departure and destination coordinates, each of them located on some street, find the length of the shortest route between them assuming that cars can only move along the streets. You are guaranteed that at least one of the coordinates is an integer.
I am struggling a little to figure out the logic here. There are many cases and I don't know how to accommodate them all. This is what I have so far
double perfectCity(double[] departure, double[] destination) {
double yDist = Math.abs(destination[1]-departure[1]);
double xDist = Math.abs(departure[1] - departure[0] + departure[1]-destination[0]);
return xDist + yDist;
}
The algorithm is very simple if the inputs are integers, just find the absolute value between the x and y coordinates and then add them together. This is called the Manhattan distance.
int distance = Math.abs(x1 - x2) + Math.abs(y1 - y2);
With doubles, it is almost exactly the same, except for one situation. Here are some possibilities:
Both points have integer coordinates
One point has integer coordinates, and the other point has only one integer coordinate
Both points have only one integer coordinate, but they are on different axes.
Both points have only one integer coordinate, and they are on the same axis.
Possibilities 1-3 all work fine using the same algorithm as for finding distance with integers, except #4 has the possibility of the axis in common being on the same block.
For example, if the inputs were: {x: 0.5, y: 2} and {x: 0.5, y: 3} you would have to travel horizontally, vertically, and then backwards horizontally again in order to reach the destination. This is different from inputs of {x: 0.5, y: 2} and {x: 1.5, y: 3} because there is no need to travel backwards on the same axis.
So you can use the normal algorithm in all cases except for the case of when both of the Xs or Ys have floating-point values and have the same floor-ed value.
Your code should look something like this.
import static java.lang.Math.*;
public static double perfectCity(double x1, double y1, double x2, double y2) {
double xDist = abs(x1 - x2);
double yDist = abs(y1 - y2);
if (floor(x1) != x1 && floor(x2) != x2 && // both Xs are doubles
floor(x1) == floor(x2) && // on the same block
y1 != y2) { // not on the same street
xDist = min(abs(x1 - floor(x1) + x2 - floor(x2)),
abs(x1 - ceil(x1) + x2 - ceil(x2)));
} else if (floor(y1) != y1 && floor(y2) != y2 && // both Ys are doubles
floor(y1) == floor(y2) && // on the same block
x1 != x2) { // not on the same street
yDist = min(abs(y1 - floor(y1) + y2 - floor(y2)),
abs(y1 - ceil(y1) + y2 - ceil(y2)));
}
return xDist + yDist;
}
This can be much further simplified by using a helper function to calculate each axis separately.
public static double perfectCity(double x1, double y1, double x2, double y2) {
return travelOnAxis(x1, x2, y1 == y2) + travelOnAxis(y1, y2, x1 == x2);
}
private static double travelOnAxis(double from, double to, boolean travelIsStraight) {
if (Math.floor(from) == Math.floor(to) && !travelIsStraight) {
double dist = Math.abs((from % 1) + (to % 1));
return Math.min(dist, 2 - dist);
} else {
return Math.abs(from - to);
}
}
I used the trick with 2 - dist here because it's the same as calculating
Math.abs((1 - (from % 1)) + (1 - (to % 1)))
which is the same as
Math.abs(from - Math.ceil(from) + to - Math.ceil(to))
If this is a square grid, you can consider the x and y coordinates separately; the minimum distance is the sum of the minumum distances in the two directions.
In the p-direction (either x or y), you have to move from p1 to p2. From p1, you can either move to floor(p1) or ceil(p1) to get to a road (which may be equal, if p1 is an integer); from there, you can move to either floor(p2) or ceil(p2), the road on which p2 is located; from there, you can move to p2.
So, the minimum distance in the p-direction is
min(abs(p1 - ceil(p1) ) + abs(ceil(p1) - floor(p2)) + abs(floor(p2) - p2), # (1)
abs(p1 - floor(p1)) + abs(floor(p1) - ceil(p2) ) + abs(ceil(p2) - p2), # (2)
abs(p1 - floor(p1)) + abs(floor(p1) - floor(p2)) + abs(floor(p2) - p2), # (3)
abs(p1 - ceil(p1) ) + abs(ceil(p1) - ceil(p2) ) + abs(ceil(p2) - p2)) # (4)
So you can just calculate this independently for the x and y directions, and add.
To illustrate this (abbreviating floor and ceil as f and p respectively):
f(p1) p1 c(p1)
+---O>>>>+>>>>>>>>+
.
.
+>>>O----+
f(p2) p2 c(p2)
--------------------------------> p axis
The shortest route is indicated here with >. The .s are on the shortest route, but since that part of the route is orthogonal to the p direction, it "doesn't count" towards the minimum distance in that direction.
The minimum route shown here, p1 -> c(p1) -> f(p2) -> p2, is Case 1 above.
It should not be hard to visualize swapping p1 and p2, in which case the minimum route is to go from p1 ->f(p1) -> c(p2) -> p2 (Case 2).
The case of pN == f(pN) == c(pN) is not very different; then, the part of the expression abs(pN - f(pN)) or abs(pN - c(pN)) is just zero.
The slightly different case is where f(p1) == f(p2):
f(p1) p1 c(p1) f(p1) p1 c(p1)
+---O>>>>+ +<<<O----+
. .
. .
+-----O<<+ +>>>>>O--+
f(p2) p2 c(p2) f(p2) p2 c(p2)
--------------------------------> p axis
In this case, the minimum route can either be p1 -> f(p1) -> f(p2) -> p2 or p1 -> c(p1) -> c(p2) -> p2 (which are Cases 3 and 4, respectively).
As mentioned by 4castle, the problem is trivial if only integers are considered for input. You would never have to "move back" after having "moved forward" in that case since you would always reach your destinaton in a single move.
But since, at most one floating point number needs to be considered for each of departure/destination, we need to consider 3 cases, (warning: lengthy explanation). Below is a python2 implementation with explanations.
x co-ordinates of both departure and destination are the same and are not floating point numbers. In this case, the shortest distance is simply the absolute difference between y co-ordinates. The same logic applies vice-versa.
import math
class Location():
def __init__(self, cord):
self.x = cord[0]
self.y = cord[1]
def perfectCity(departure, destination):
l1 = Location(departure)
l2 = Location(destination)
if l1.x == l2.x and float(l1.x).is_integer() and float(l2.x).is_integer():
return abs(l1.y-l2.y)
if l1.y == l2.y and float(l1.y).is_integer() and float(l2.y).is_integer():
return abs(l1.x-l2.x)
When one of the co-ordinates in the departure is a floating point, then:
If x co-ordinate is floating point, we can move backwards(round down) or move front(round up).
If y co-ordinate is floating point, we can either move down (round down) or move up (round up).
The above logic should work even when there is no floating point co-ordinate since we move in either direction by zero units.
Once we calculate these, we just choose the minimum among those like below,
return min(calc_round_up_dist(l1, l2), cal_round_down_dist(l1, l2))
Lets take an example of (0.4, 1) and (0.9, 3) for below calculations.
While calculating the round_up we need to calculate 3 distances:
round_up_distance: difference between the rounded up value of the floating point co-ordinate and the original floating point co-ordinate. We return zero if there is no floating point co-ordinate. 1 - 0.4 = 0.6 in the above example
non_floating_point difference: difference between the non floating point co-ordinate of departure and the corresponding co-ordinate of destination ( note that this might be floating point or not a floating point abs(3-1) = 2 in the above example
Difference between departure's floating point counterpart in the destination co-ordinate 0.9 in the above case and the new value of departure's floating point after rounding up, 0.4 + 0.6(this is the round_up distance) = 1.0, i.e. abs(0.9 - 1.0) = 0.1
Adding all the 3 above we get 0.6 + 2 + .1 = 2.7 which is the shortest distance.
Corresponding calculation needs to be done for rounding down. And we pick the minimum among both. The code for round_up and round_down is as below,
import math
class Location():
def __init__(self, cord):
self.x = cord[0]
self.y = cord[1]
def floating_point_round_up(self):
if not float(self.x).is_integer():
return math.ceil(self.x) - self.x
if not float(self.y).is_integer():
return math.ceil(self.y) - self.y
return 0
def floating_point_round_down(self):
if not float(self.x).is_integer():
return self.x - math.floor(self.x)
if not float(self.y).is_integer():
return self.y - math.floor(self.y)
return 0
def non_floating_point_diff(self, obj):
if not float(self.x).is_integer():
return abs(self.y - obj.y)
if not float(self.y).is_integer():
return abs(self.x - obj.x)
return abs(self.y - obj.y)
def floating_point_counterpart(self, obj):
if not float(self.x).is_integer():
return obj.x
if not float(self.y).is_integer():
return obj.y
return obj.x
def floating_point(self):
if not float(self.x).is_integer():
return self.x
if not float(self.y).is_integer():
return self.y
return self.x
Round up and down functions are as below,
def calc_round_up_dist(l1, l2):
dist = l1.floating_point_round_up()
diff = l1.non_floating_point_diff(l2)
floating_point_counterpart = l1.floating_point_counterpart(l2)
new_val = dist + l1.floating_point()
return dist + diff + abs(new_val - floating_point_counterpart)
def cal_round_down_dist(l1, l2):
dist = l1.floating_point_round_down()
diff = l1.non_floating_point_diff(l2)
floating_point_counterpart = l1.floating_point_counterpart(l2)
new_val = l1.floating_point() - dist
return dist + diff + abs(floating_point_counterpart - new_val)
Finally the main function that calls the above methods,
def perfectCity(departure, destination):
l1 = Location(departure)
l2 = Location(destination)
if l1.x == l2.x and float(l1.x).is_integer() and float(l2.x).is_integer():
return abs(l1.y-l2.y)
if l1.y == l2.y and float(l1.y).is_integer() and float(l2.y).is_integer():
return abs(l1.x-l2.x)
return min(calc_round_up_dist(l1, l2), cal_round_down_dist(l1, l2))
This is a practice question on CodeSignal:
https://app.codesignal.com/company-challenges/uber/gsjPcfsuNavxhsQQ7
def solution(departure, destination):
# go to the closest integer
# I can only travel the path of an integer
# if the number is a float I need to travel to an integer first
# then travel to the destination
x1, y1 = departure
x2, y2 = destination
res = 0
# check if the coordinations are integers
a = list(map(isInteger, departure))
b = list(map(isInteger, destination))
# if all are integers or if the corresponding elements are different
if a[0] ^ b[0] or (a[0] and a[1] and b[0] and b[1]):
return abs(x1-x2) + abs(y1-y2)
if a[0]:
res += abs(x2-x1)
# cloest distance from y1 to y2
res += getClosest(y1, y2)
else:
res += abs(y2-y1)
# closes distance from x1 to x2
res += getClosest(x1, x2)
return res
def getClosest(y1, y2):
cand1 = math.floor(y1)
cand2 = math.ceil(y1)
# find the integer closer to y1 to move to
res1 = abs(y1-cand1) + abs(cand1-y2)
res2 = abs(y1-cand2) + abs(cand2-y2)
return min(res1, res2)
def isInteger(n):
return n == round(n)
Related
Imagine slicing a polygon like a pizza haphazardly, how would you find the largest slice?
I have a polygon that have been divided up with multiple lines, creating new smaller polygons that make up the whole. How would I go about finding the slice with the largest area? Imagine something like this: sliced polygon green points are vertices, lines intersect creating more vertices, looking for the largest yellow marked area. I figured this could be solved by generating a directed graph in order to define each unique shape. I can't come up with a way to link all vertices correctly though. All vertices and edge lengths are either given or calculated with these methods. public static double calcDistanceBetweenPoints(Point a, Point b){ return Math.sqrt((b.y - a.y) * (b.y - a.y) + (b.x - a.x) * (b.x - a.x)); } public static Point findIntersection(Point A, Point B, Point C, Point D){ // Line AB represented as a1x + b1y = c1 double a1 = B.y - A.y; double b1 = A.x - B.x; double c1 = a1*(A.x) + b1*(A.y); // Line CD represented as a2x + b2y = c2 double a2 = D.y - C.y; double b2 = C.x - D.x; double c2 = a2*(C.x)+ b2*(C.y); double determinant = a1*b2 - a2*b1; if (determinant == 0) { // The lines are parallel return new Point(Double.MAX_VALUE, Double.MAX_VALUE); } else { double x = (b2*c1 - b1*c2)/determinant; double y = (a1*c2 - a2*c1)/determinant; return new Point(x, y); } } Data collected from the System.in input stream looks something like this: n m x1 y1 x.. y... xn yn x11 y11 x21 y21 x.. y.. x.. y.. x1m y1m x2m y2m So I get all the starting and ending points for each line from the input. Thanks for the help
Find points on triangle
I have 3 vertices of a triangle and I'm trying to find all the integer points that lie on the inside and ON THE SIDES of the triangle. I've tried numerous methods and they all succeed in finding the inside points, but fail in finding the points on the sides of the triangle. Currently I'm using barycentric coordinates: private static boolean pointInTriangle(int[] p, int[] c1, int[] c2, int[] c3){ float alpha = ((c2[1] - c3[1])*(p[0] - c3[0]) + (c3[0] - c2[0])*(p[1] - c3[1])) / ((c2[1] - c3[1])*(c1[0] - c3[0]) + (c3[0] - c2[0])*(c1[1] - c3[1])); float beta = ((c3[1] - c1[1])*(p[0] - c3[0]) + (c1[0] - c3[0])*(p[1] - c3[1])) / ((c2[1] - c3[1])*(c1[0] - c3[0]) + (c3[0] - c2[0])*(c1[1] - c3[1])); float gamma = 1.0f - alpha - beta; return ( (alpha>=0.0f) && (beta>=0.0f) && (gamma>=0.0f) ); For example, for vertices (0,0),(0,10),(10,10) this does find (10,8) but it also finds (11,8) which is not correct. Can somebody help me? Thanks in advance!
Use the code you alreay have to find if a position is inside the triangle. Then for the other part, if a point is on the line or not.. I would do it like this.. Check by calculating the distance between 2 vertices at a time. Lets say we have vertices a, b and c. And the point p. Check if p is on the line between a and b. This can be done by measuring the distance between a -> p and p -> b. If those two distances equals the distance of a -> b then it is on the line. If p should be off the line the distance will be longer. Here is a method to caluclate distance (pythagoran teorem): private static double GetDistance(double x1, double y1, double x2, double y2) { double a = Math.abs(x1-x2); double b = Math.abs(y1-y2); return Math.sqrt(a * a + b * b); }
Check is a point (x,y) is between two points drawn on a straight line
I have drawn a line between two points A(x,y)---B(x,y) Now I have a third point C(x,y). I want to know that if C lies on the line which is drawn between A and B. I want to do it in java language. I have found couple of answers similar to this. But, all have some problems and no one is perfect.
if (distance(A, C) + distance(B, C) == distance(A, B)) return true; // C is on the line. return false; // C is not on the line. or just: return distance(A, C) + distance(B, C) == distance(A, B); The way this works is rather simple. If C lies on the AB line, you'll get the following scenario: A-C------B and, regardless of where it lies on that line, dist(AC) + dist(CB) == dist(AB). For any other case, you have a triangle of some description and 'dist(AC) + dist(CB) > dist(AB)': A-----B \ / \ / C In fact, this even works if C lies on the extrapolated line: C---A-------B provided that the distances are kept unsigned. The distance dist(AB) can be calculated as: ___________________________ / 2 2 V (A.x - B.x) + (A.y - B.y) Keep in mind the inherent limitations (limited precision) of floating point operations. It's possible that you may need to opt for a "close enough" test (say, less than one part per million error) to ensure correct functioning of the equality.
ATTENTION! Math-only! You can try this formula. Put your A(x1, y1) and B(x2, y2) coordinates to formula, then you'll get something like y = k*x + b; // k and b - numbers Then, any point which will satisfy this equation, will lie on your line. To check that C(x, y) is between A(x1, y1) and B(x2, y2), check this: (x1<x<x2 && y1<y<y2) || (x1>x>x2 && y1>y>y2). Example A(2,3) B(6,5) The equation of line: (y - 3)/(5 - 3) = (x - 2)/(6 - 2) (y - 3)/2 = (x - 2)/4 4*(y - 3) = 2*(x - 2) 4y - 12 = 2x - 4 4y = 2x + 8 y = 1/2 * x + 2; // equation of line. k = 1/2, b = 2; Let's check if C(4,4) lies on this line. 2<4<6 & 3<4<5 // C between A and B Now put C coordinates to equation: 4 = 1/2 * 4 + 2 4 = 2 + 2 // equal, C is on line AB PS: as #paxdiablo wrote, you need to check if line is horizontal or vertical before calculating. Just check y1 == y2 || x1 == x2
I believe the simplest is // is BC inline with AC or visa-versa public static boolean inLine(Point A, Point B, Point C) { // if AC is vertical if (A.x == C.x) return B.x == C.x; // if AC is horizontal if (A.y == C.y) return B.y == C.y; // match the gradients return (A.x - C.x)*(A.y - C.y) == (C.x - B.x)*(C.y - B.y); } You can calculate the gradient by taking the difference in the x values divided by the difference in the y values. Note: there is a different test to see if C appears on the line between A and B if you draw it on a screen. Maths assumes that A, B, C are infinitely small points. Actually very small to within representation error.
The above answers are unnecessarily complicated. The simplest is as follows. if (x-x1)/(x2-x1) = (y-y1)/(y2-y1) = alpha (a constant), then the point C(x,y) will lie on the line between pts 1 & 2. If alpha < 0.0, then C is exterior to point 1. If alpha > 1.0, then C is exterior to point 2. Finally if alpha = [0,1.0], then C is interior to 1 & 2. Hope this answer helps.
I think all the methods here have a pitfall, in that they are not dealing with rounding errors as rigorously as they could. Basically the methods described will tell you if your point is close enough to the line using some straightforward algorithm and that it will be more or less precise. Why precision is important? Because it's the very problem presented by op. For a computer program there is no such thing as a point on a line, there is only point within an epsilon of a line and what that epsilon is needs to be documented. Let's illustrate the problem. Using the distance comparison algorithm: Let's say a segment goes from (0, 0) to (0, 2000), we are using floats in our application (which have around 7 decimal places of precision) and we test whether a point on (1E-6, 1000) is on the line or not. The distance from either end of the segment to the point is 1000.0000000005 or 1000 + 5E-10, and, thus, the difference with the addition of the distance to and from the point is around 1E-9. But none of those values can be stored on a float with enough precission and the method will return true. If we use a more precise method like calculating the distance to the closest point in the line, it returns a value that a float has enough precision to store and we could return false depending on the acceptable epsilon. I used floats in the example but the same applies to any floating point type such as double. One solution is to use BigDecimal and whichever method you want if incurring in performance and memory hit is not an issue. A more precise method than comparing distances for floating points, and, more importantly, consistently precise, although at a higher computational cost, is calculating the distance to the closest point in the line. Shortest distance between a point and a line segment It looks like I'm splitting hairs but I had to deal with this problem before. It's an issue when chaining geometric operations. If you don't control what kind of precission loss you are dealing with, eventually you will run into difficult bugs that will force you to reason rigorously about the code in order to fix them.
An easy way to do that I believe would be the check the angle formed by the 3 points. If the angle ACB is 180 degrees (or close to it,depending on how accurate you want to be) then the point C is between A and B.
I think this might help How to check if a point lies on a line between 2 other points That solution uses only integers given you only provide integers which removes some pitfalls as well
Here is my C# solution. I believe the Java equivalent will be almost identical. Notes: Method will only return true if the point is within the bounds of the line (it does not assume an infinite line). It will handle vertical or horizontal lines. It calculates the distance of the point being checked from the line so allows a tolerance to be passed to the method. /// <summary> /// Check if Point C is on the line AB /// </summary> public static bool IsOnLine(Point A, Point B, Point C, double tolerance) { double minX = Math.Min(A.X, B.X) - tolerance; double maxX = Math.Max(A.X, B.X) + tolerance; double minY = Math.Min(A.Y, B.Y) - tolerance; double maxY = Math.Max(A.Y, B.Y) + tolerance; //Check C is within the bounds of the line if (C.X >= maxX || C.X <= minX || C.Y <= minY || C.Y >= maxY) { return false; } // Check for when AB is vertical if (A.X == B.X) { if (Math.Abs(A.X - C.X) >= tolerance) { return false; } return true; } // Check for when AB is horizontal if (A.Y == B.Y) { if (Math.Abs(A.Y - C.Y) >= tolerance) { return false; } return true; } // Check istance of the point form the line double distFromLine = Math.Abs(((B.X - A.X)*(A.Y - C.Y))-((A.X - C.X)*(B.Y - A.Y))) / Math.Sqrt((B.X - A.X) * (B.X - A.X) + (B.Y - A.Y) * (B.Y - A.Y)); if (distFromLine >= tolerance) { return false; } else { return true; } }
def DistBetwPoints(p1, p2): return math.sqrt( (p2[0] - p1[0])**2 + (p2[1] - p1[1])**2 ) # "Check if point C is between line endpoints A and B" def PointBetwPoints(A, B, C): dist_line_endp = DistBetwPoints(A,B) if DistBetwPoints(A,C)>dist_line_endp: return 1 elif DistBetwPoints(B,C)>dist_line_endp: return 1 else: return 0
Here is a JavaScript function I made. You pass it three points (three objects with an x and y property). Points 1 and 2 define your line, and point 3 is the point you are testing. You will receive an object back with some useful info: on_projected_line - If pt3 lies anywhere on the line including outside the points. on_line - If pt3 lies on the line and between or on pt1 and pt2. x_between - If pt3 is between or on the x bounds. y_between - If pt3 is between or on the y bounds. between - If x_between and y_between are both true. /** * #description Check if pt3 is on line defined by pt1 and pt2. * #param {Object} pt1 The first point defining the line. * #param {float} pt1.x * #param {float} pt1.y * #param {Object} pt2 The second point defining the line. * #param {float} pt2.x * #param {float} pt2.y * #param {Object} pt3 The point to test. * #param {float} pt3.x * #param {float} pt3.y */ function pointOnLine(pt1, pt2, pt3) { const result = { on_projected_line: true, on_line: false, between_both: false, between_x: false, between_y: false, }; // Determine if on line interior or exterior const x = (pt3.x - pt1.x) / (pt2.x - pt1.x); const y = (pt3.y - pt1.y) / (pt2.y - pt1.y); // Check if on line equation result.on_projected_line = x === y; // Check within x bounds if ( (pt1.x <= pt3.x && pt3.x <= pt2.x) || (pt2.x <= pt3.x && pt3.x <= pt1.x) ) { result.between_x = true; } // Check within y bounds if ( (pt1.y <= pt3.y && pt3.y <= pt2.y) || (pt2.y <= pt3.y && pt3.y <= pt1.y) ) { result.between_y = true; } result.between_both = result.between_x && result.between_y; result.on_line = result.on_projected_line && result.between_both; return result; } console.log("pointOnLine({x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 2})") console.log(pointOnLine({x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 2})) console.log("pointOnLine({x: 0, y: 0}, {x: 1, y: 1}, {x: 0.5, y: 0.5})") console.log(pointOnLine({x: 0, y: 0}, {x: 1, y: 1}, {x: 0.5, y: 0.5}))
if ( (ymid - y1) * (x2-x1) == (xmid - x1) * (y2-y1) ) **is true, Z lies on line AB** Start Point : A (x1, y1), End Point : B (x2, y2), Point That is on Line AB or Not : Z (xmid, ymid) I just condensed everyone's answers and this formula works the best for me. It avoids division by zero No distance calculation required Simple to implement Edit: In case you are dealing with floats, which you most probably are, use this: if( (ymid - y1) * (x2-x1) - (xmid - x1) * (y2-y1) < DELTA ) where the tolerance DELTA is a value close to zero. I usually set it to 0.05
How to draw a smooth line through a set of points using Bezier curves?
I need to draw a smooth line through a set of vertices. The set of vertices is compiled by a user dragging their finger across a touch screen, the set tends to be fairly large and the distance between the vertices is fairly small. However, if I simply connect each vertex with a straight line, the result is very rough (not-smooth). I found solutions to this which use spline interpolation (and/or other things I don't understand) to smooth the line by adding a bunch of additional vertices. These work nicely, but because the list of vertices is already fairly large, increasing it by 10x or so has significant performance implications. It seems like the smoothing should be accomplishable by using Bezier curves without adding additional vertices. Below is some code based on the solution here: http://www.antigrain.com/research/bezier_interpolation/ It works well when the distance between the vertices is large, but doesn't work very well when the vertices are close together. Any suggestions for a better way to draw a smooth curve through a large set of vertices, without adding additional vertices? Vector<PointF> gesture; protected void onDraw(Canvas canvas) { if(gesture.size() > 4 ) { Path gesturePath = new Path(); gesturePath.moveTo(gesture.get(0).x, gesture.get(0).y); gesturePath.lineTo(gesture.get(1).x, gesture.get(1).y); for (int i = 2; i < gesture.size() - 1; i++) { float[] ctrl = getControlPoint(gesture.get(i), gesture.get(i - 1), gesture.get(i), gesture.get(i + 1)); gesturePath.cubicTo(ctrl[0], ctrl[1], ctrl[2], ctrl[3], gesture.get(i).x, gesture.get(i).y); } gesturePath.lineTo(gesture.get(gesture.size() - 1).x, gesture.get(gesture.size() - 1).y); canvas.drawPath(gesturePath, mPaint); } } } private float[] getControlPoint(PointF p0, PointF p1, PointF p2, PointF p3) { float x0 = p0.x; float x1 = p1.x; float x2 = p2.x; float x3 = p3.x; float y0 = p0.y; float y1 = p1.y; float y2 = p2.y; float y3 = p3.y; double xc1 = (x0 + x1) / 2.0; double yc1 = (y0 + y1) / 2.0; double xc2 = (x1 + x2) / 2.0; double yc2 = (y1 + y2) / 2.0; double xc3 = (x2 + x3) / 2.0; double yc3 = (y2 + y3) / 2.0; double len1 = Math.sqrt((x1-x0) * (x1-x0) + (y1-y0) * (y1-y0)); double len2 = Math.sqrt((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1)); double len3 = Math.sqrt((x3-x2) * (x3-x2) + (y3-y2) * (y3-y2)); double k1 = len1 / (len1 + len2); double k2 = len2 / (len2 + len3); double xm1 = xc1 + (xc2 - xc1) * k1; double ym1 = yc1 + (yc2 - yc1) * k1; double xm2 = xc2 + (xc3 - xc2) * k2; double ym2 = yc2 + (yc3 - yc2) * k2; // Resulting control points. Here smooth_value is mentioned // above coefficient K whose value should be in range [0...1]. double k = .1; float ctrl1_x = (float) (xm1 + (xc2 - xm1) * k + x1 - xm1); float ctrl1_y = (float) (ym1 + (yc2 - ym1) * k + y1 - ym1); float ctrl2_x = (float) (xm2 + (xc2 - xm2) * k + x2 - xm2); float ctrl2_y = (float) (ym2 + (yc2 - ym2) * k + y2 - ym2); return new float[]{ctrl1_x, ctrl1_y, ctrl2_x, ctrl2_y}; }
Bezier Curves are not designed to go through the provided points! They are designed to shape a smooth curve influenced by the control points. Further you don't want to have your smooth curve going through all data points! Instead of interpolating you should consider filtering your data set: Filtering For that case you need a sequence of your data, as array of points, in the order the finger has drawn the gesture: You should look in wiki for "sliding average". You should use a small averaging window. (try 5 - 10 points). This works as follows: (look for wiki for a more detailed description) I use here an average window of 10 points: start by calculation of the average of points 0 - 9, and output the result as result point 0 then calculate the average of point 1 - 10 and output, result 1 And so on. to calculate the average between N points: avgX = (x0+ x1 .... xn) / N avgY = (y0+ y1 .... yn) / N Finally you connect the resulting points with lines. If you still need to interpolate between missing points, you should then use piece - wise cubic splines. One cubic spline goes through all 3 provided points. You would need to calculate a series of them. But first try the sliding average. This is very easy.
Nice question. Your (wrong) result is obvious, but you can try to apply it to a much smaller dataset, maybe by replacing groups of close points with an average point. The appropriate distance in this case to tell if two or more points belong to the same group may be expressed in time, not space, so you'll need to store the whole touch event (x, y and timestamp). I was thinking of this because I need a way to let users draw geometric primitives (rectangles, lines and simple curves) by touch
What is this for? Why do you need to be so accurate? I would assume you only need something around 4 vertices stored for every inch the user drags his finger. With that in mind: Try using one vertex out of every X to actually draw between, with the middle vertex used for specifying the weighted point of the curve. int interval = 10; //how many points to skip gesture.moveTo(gesture.get(0).x, gesture.get(0).y); for(int i =0; i +interval/2 < gesture.size(); i+=interval) { Gesture ngp = gesture.get(i+interval/2); gesturePath.quadTo(ngp.x,ngp.y, gp.x,gp.y); } You'll need to adjust this to actually work but the idea is there.
Moving from xy to another point, where am I at time t?
How would I write a function to move from point1 to point2 given some time? For example: Point move(Point point1, Point point2, long timeInMilliseconds, int speedPerSecond) { // basic stuff int pointsMoved = speedPerSecond * 1000 / timeInMilliseconds; if (point1.x == point2.x && point1.y > point2.y) return (new Point(point1.x, Math.min(point2.y, point1.y + pointsMoved))); ... } Yes, that's where my sad math skills end. How do I move if the movement is not diagonal or vertical? if there's an angle? BTW, I plan to recalculate the current point based on point1 and point2, I will not be updating point1 nor point2 from the caller, so caller would look like this: Point currentPoint = move(originalPoint, finalPoint, getCurrentTime() - originalTime, 10); The signature of the function doesn't have to be what I mentioned. It could very well use degrees, but that's going to be another thing to figure out, if I have to use degrees.
Here's the general motion formula: p = k⟨p2 - p1⟩ + p1 p1 is the initial position. p2 is the final position. p is the current location. k is a ratio, usually between 0 and 1, that determines how much of the distance to p2 we've covered. Your function receives tn, the current time, and v, the speed from the p1 to p2. Therefore we need one additional piece to calculate k: the distance from p1 to p2. tn is in time units (t), the distance |p2 - p1| is in distance units (d), and the speed is in distance per time units (d / t). k is unitless, so we have to neutralize the units in the three values. d / (d / t) / t = d / d · t / t = 1 and our units are neutralized. So we have: k = |p2 - p1| / v / tn The distance is easily determined via the Pythagorean Theorem, giving us k. From there we decompose the general formula into its components: px = k(x2 - x1) + x1 py = k(y2 - y1) + y1 k, being unitless despite containing elements with components, does not get decomposed.