Count points in a rectangle

前端 未结 9 1480
失恋的感觉
失恋的感觉 2020-12-29 23:53

I have lots (billions) of points in 2D which I can preprocess and I would like to answer queries which are of the following form:

Given all four corners of a rectang

9条回答
  •  死守一世寂寞
    2020-12-30 00:29

    I would start with presorting the points array along any axis (let it be x). Then binary searching it for the points with x-projection in rectangles' bounding box x-projection. That along would of reduce the numbers of points to check drastically.

    Then we can filter the points further just by checking if they are in rectangles bounding box. But yes, that would be linear.

    Then we may take a transformation matrix for the rectangle (I assume we already have it). Rectangle is an affine transformation of singular 2-cube, therefore we can find reverse transformation without calculating an actual inverse matrix.

    For direct transform matrix of

    A D a
    B E b
    C F c
    

    the solution would be:

    d = 1/(AE − BD)
    
    A' = Ed
    B' = −Bd
    C' = (BF − EC)d
    
    D' = −Dd
    E' = Ad
    F' = (DC − AF)d
    
    a' = b' = 0
    c' = 1
    

    Then, by applying inverse transform to every point, we will either translate it into a singular cube, which is (0, 1)x(0, 1), if it originally lies in a rectangle, or not if it doesn't.

    UPD: Or, instead of all the transformation stuff, you can do the following:

    Let points of rectangle be P1..P4 and the point to check A.

    For i = 1..4 calculate PAi as Pi - A

    Now the cross product of (Pi.x, Pi.y, 0)x(Pj.x, Pj.y, 0) would measure the triangle made by an A and corresponding rectangles' edge. And, as original point are all on xy plane, the result would be like (0, 0, Sij), where Sij is the signed square of a triangle. Just calculate the sum:

    |(P1.x, P1.y, 0)x(P2.x, P2.y, 0)[3]|+
    |(P2.x, P2.y, 0)x(P3.x, P3.y, 0)[3]|+
    |(P3.x, P3.y, 0)x(P4.x, P4.y, 0)[3]|+
    |(P4.x, P4.y, 0)x(P1.x, P1.y, 0)[3]|
    

    And compare it with the rectangles square. If it is more or less equal, then the point is in the rectangle. There would be some small computational error, so the exact equality is out of the question.

提交回复
热议问题