058 判断一个点是否在矩形内部
Table of Contents

ac

在二维坐标系中,所有的值是double类型,那么一个矩形可以由四个点来代表,(x1, y1)为最左的点,(x2, y2)为最上的点,(x3, y3)为最下的点,(x4, y4)为最右的点。给定4个点代表的矩形,再给定一个点(x, y),判断(x, y)是否在矩形中
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;


public class Main {

    public static Scanner sc = new Scanner(System.in);

    static int M = (int)Math.pow(10, 9) + 7;

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));


    public static void main(String[] args) throws Exception{
        double[][] rec = new double[4][2];
        for(int i=0;i<4;i++){
            String line = reader.readLine();
            String[] strArr = line.split(" ");
            rec[i][0] = Double.valueOf(strArr[0]);
            rec[i][1] = Double.valueOf(strArr[1]);
        }
        String line = reader.readLine();
        String[] strArr = line.split(" ");
        double x = Double.valueOf(strArr[0]);
        double y = Double.valueOf(strArr[1]);
        System.out.println(process(rec,x,y) ? "Yes" : "No");

    }

    // 矩形平行与x轴(或y轴)
    static boolean isInside(double x1, double y1, double x4, double y4, double x, double y){
        if(x <= x1 || x >= x4){
            return false;
        }
        if(y <= y4 || y >= y1){
            return false;
        }
        return true;
    }

    static boolean process(double[][] rec, double x, double y){
        if(rec[0][1] == rec[1][1]){
            return isInside(rec[0][0], rec[0][1], rec[3][0], rec[3][1], x, y);
        }
        // 坐标变换
        // 长,宽
        double l = Math.abs(rec[3][1] - rec[2][1]);
        double k = Math.abs(rec[3][0] - rec[2][0]);
        double s = Math.sqrt(k*k+l*l);
        double sin = l / s;
        double cos = k / s;
        double x1R = rec[0][0] * cos  + sin * rec[0][1];
        double y1R = -rec[0][0] * sin  + cos * rec[0][1];
        double x4R = rec[3][0] * cos  + sin * rec[3][1];
        double y4R = -rec[3][0] * sin  + cos * rec[3][1];
        double xR = x * cos  + sin * y ;
        double yR = -x * sin  + cos * y;
        return isInside(x1R, y1R, x4R, y4R, xR, yR);
    }

}
/*
                     (x2, y2)
(x1, y1)

                           (x4, y4)
      (x3, y3)

                               (rec[1][0], rec[1][1])
(rec[0][0], rec[0][1])

                                          (rec[3][0], rec[3][1])
      (rec[2][0], rec[2][1])

2.00 2.50
3.00 5.00
3.00 1.50
4.00 4.00
3.21 3.78

Yes

2.00 2.50
3.00 5.00
3.00 1.50
4.00 4.00
2333.33 2333333.33

No
 */