How many integer points within the three points forming a triangle?

后端 未结 13 1326
一个人的身影
一个人的身影 2020-12-12 21:04

Actually this is a classic problem as SO user Victor put it (in another SO question regarding which tasks to ask during an interview).

I couldn\'t do it in an hour

13条回答
  •  生来不讨喜
    2020-12-12 21:51

    Quick n'dirty pseudocode:

    -- Declare triangle
    p1 2DPoint = (x1, y1);
    p2 2DPoint = (x2, y2);
    p3 2DPoint = (x3, y3);
    triangle [2DPoint] := [p1, p2, p3];
    
    -- Bounding box
    xmin float = min(triangle[][0]);
    xmax float = max(triangle[][0]);
    ymin float = min(triangle[][1]);
    ymax float = max(triangle[][1]);
    
    result [[float]];
    
    -- Points in bounding box might be inside the triangle
    for x in xmin .. xmax {
      for y in ymin .. ymax {
        if a line starting in (x, y) and going in any direction crosses one, and only one, of the lines between the points in the triangle, or hits exactly one of the corners of the triangle {
          result[result.count] = (x, y);
        }
      }
    }
    

提交回复
热议问题