tags:

views:

544

answers:

5

I have this matrix

/// as if the create a rectangle
int [][] loc = {
  {5, 15},//(x1, y1)
  {5, 30}, // (x1, y2)
  {20, 15},// (x2, y1)
  {20, 30}, // (x2, y2)
}

// this are the point that i want to check if they are in the rectangular range or not
int [] [] point = {
  {6, 16}, //(x, y)
  {3, 17}, //(x, y)
}

I want i method that can take the point and search if it in the loc range or not by using x1<x<x2 and y1<y<y2

+5  A: 

A point (x, y) is inside a rectangle (x1,y1) - (x2, y2) if

(x1 <= x <= x2) and (y1 <= y <= y2)

Your code should look like this (this actually is C code, but JavaScript shouldn't be much different):

 x1 = loc[0][0];
 x2 = loc[2][0];
 y1 = loc[0][1];
 y2 = loc[2][1];
 for (int i = 0; i < num_points; i++) {
   if ((x1 <= point[i][0] <= x2) && (y2 <= point[i][1] <= y2)) {
     // This point is inside the rectangle - insert code here
   } else {
     // This point is not inside the rectangle - insert code here
   }
 }

Note that this will only work if (x1 <= x2) and (y1 <= y2), so you might perhaps make sure by using this instead the first four lines above:

x1 = Math.Min(loc[0][0], loc[2][0]);
x2 = Math.Max(loc[0][0], loc[2][0]);
y1 = Math.Min(loc[0][1], loc[2][1]);
y2 = Math.Max(loc[0][1], loc[2][1]);
schnaader
schnaader;Can you explain for me more a bout what you mean ?
ok by this way i need to have a min method right?
JavaScript should be able to do this for you if you use Math.Min and Math.Max, I'll update my answer.
schnaader
+3  A: 

Oh, come on.

Why don't you define what you mean by "in".

I bet if you do that, an algorithm for testing if a point is "in" naturally falls of of the definition.

We'll wait right here while you do that, ok?

tpdi
A: 

I mean by "in" that it is within the range by using x1 < x < x2 and y1 < y < y2

Shamsa, here's a stackoverflow.com usage tip. Don't post another answer in response to another answer. Post a comment instead like I did here. This site's usage is a little different then other forums.
zooropa
OKay now I get it >>>
sorry, but how i can delete it?
a first time user with no rep might not be able to comment or delete yet...
Tom
He can comment on answers to his questions, I'm not sure if he can delete his answers though.
Paolo Bergantino
A: 

schnaader;

Can you explain for me more a bout what you mean ?

You are supposed to comment on answers by adding a comment to an answer (add comment link below each answer). Writing a new answer is supposed to be an answer to the original question, not a refinement or comment. This is not a forum.
OregonGhost
A: 

Hello! but the solution presented by schnaader, is for two point (x1,y1) and (x2,y2) but we have four points in rectangle, My question for 4 points how this code will look like e.g. above code for find min of x cordinates should look like x1=math.min(x1,x2,x3,x4). am i right??

Please ask this as a new question referencing this one.
Marc Gravell