views:

63

answers:

3

Problem illustration

Given a rectangle of width w and height h. and a coordinate x,y in that rectangle I would like to identify which triangle I am within.

i.e. the function should take parameters(x,y) and return a,b,c,d or a zero based number representing that triangle index i.e. (0=A,1=B,2=C,3=D) if they are in that order.

I think this would be something like >= the formula of the red line and >= the formula of the green line?

I'd like to implement this in VB.NET

+1  A: 

I would consider the angle of the line to the point from the top left and top right corners. If it is less than 45 degrees (adjusting for the base direction of the edge) in both cases then the point is in C. Other combinations will cover the other three triangles.

You don't actually need to calculate inverse trig functions to do this, as the ratio of the lengths of the lines gives you enough information (and sin(45)... or rather sin(pi/4) is a fixed value).

Richard
+5  A: 
aboveRed = x*h > y*w;
aboveGreen = (w-x)*h > y*w;
if (aboveRed)
{
    if (aboveGreen) return "C"; else return "B";
}
else
{
    if (aboveGreen) return "D"; else return "A";
}
Vlad
ahh this looks good
PeanutPower
+2  A: 

Equation of green line: h * x + w * y = h * w

Equation of red line: x * h - y * w = 0

Public Function GetTriangleNumber(ByVal x As Integer, ByVal y As Integer) 
                                                                     As Integer
    Dim overGreenLine As Boolean = ((((h * x) + (w * y)) - (h * w)) < 0)
    Dim overRedLine As Boolean = (((h * x) - (w * y)) > 0)
    If overGreenLine Then
        Return IIf(overRedLine, 2, 3)
    End If
    Return IIf(overRedLine, 1, 0)
End Function
DreamWalker
thanks i gave an upvote for the VB code but accepted Vlad's answer as he got there first with the algorithm
PeanutPower