2009-04-29 10 views
4

私はこの行列ポイント・イン・長方形の試験

/// 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) 
} 

を持って、私はポイントを取ると、それLOCの範囲内かどうか x1<x<x2y1<y<y2

+0

矩形を定義するには、2つの点(対角線上の2つの点を選択)または2つのx値と2つのy値が必要です。 –

+0

とにかく、軸に沿った長方形... – Skilldrick

+0

このコードはjavascriptですか? –

答えて

14

Aを使用している場合、検索することができ、私の方法をしたいです点(x、y)は、矩形の内側にある(X1、Y1) - (X2、Y2)

(X1 < = X < = X2)(Y1 < = Y場合(X1 <が= x2の場合にのみ動作すること

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]) && (point[i][0] <= x2) && 
     (y1 <= point[i][1]) && (point[i][1] <= y2)) { 
    // This point is inside the rectangle - insert code here 
    } else { 
    // This point is not inside the rectangle - insert code here 
    } 
} 

注:= Y2)

あなたのコードは、この(これは実際にはCのコードですが、JavaScriptが異なるあまりすべきではない)のようになります。あなたはおそらく最初の4行を超える代わりにこれを使用して確認してください可能性がある)と(Y1 < = Y2)、よう:質問が広範囲に回答されているが

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]); 
+0

schnaader; あなたは私が何を意味するのかをもっと説明できますか? –

+0

このように私は分の方法が必要ですか? –

+0

Math.MinとMath.Maxを使用する場合、JavaScriptがこれを行うことができるはずです。答えを更新します。 – schnaader

6

、私はコードの私の作品を共有したいですもっと直感的に見えるので高校時代の数学のように。念のために人々が理由在宅ワークのアップこの質問を見て:)

function between(min, p, max){ 
    result = false; 

    if (min < max){ 
    if (p > min && p < max){ 
     result = true; 
    } 
    } 

    if (min > max){ 
    if (p > max && p < min){ 
     result = true 
    } 
    } 

    if (p == min || p == max){ 
    result = true; 
    } 

    return result; 
} 

function point_in_rectagnle(x, y, left, top, right, bottom){ 
    result = false; 

    if (between(left,x,right) && between(top,y,bottom)){ 
    result = true; 
    } 
    return result; 
} 
+0

これは非常に素晴らしいエレガントな解決策です。 – jolyonruss

4

問題のコードは、JavaやCまたは{}で配列リテラルを定義する他のいくつかの言語ですが、タグはJavascriptとこのですので、 GoogleのJavascriptに表示されますが、ここでJSの点矩形の交点を行う合理的な方法です。

function pointRectangleIntersection(p, r) { 
    return p.x > r.x1 && p.x < r.x2 && p.y > r.y1 && p.y < r.y2; 
} 

var point = {x: 1, y: 2}; 
var rectangle = {x1: 0, x2: 10, y1: 1, y2: 7}; 
pointRectangleIntersection(point, rectangle); 
+0

本当に 'p.x> = r.x1'にするべきです(yと同じです)。 あなたの四角形がインクルーシブか排他的かに応じて、y2 _may_は '<='である必要があります – Anonymouse