碰到一个面试题,大致意思如标题,如果面试过了别忘了点赞关注。
这个问题给出两个长方形的坐标,问这两个长方形是否有重合部分。画出图来就是这样的:
主要逻辑有人解释过了,我直接上代码
https://blog.csdn.net/weixin_34195364/article/details/94221416
import java.util.Random;
public class Rectangle {
int PLx=0;
int PLy=0;
int PRx=0;
int PRy=0;
void setvalues(){
Random random = new Random();
while (PLx>=PRx){
PLx=random.nextInt(100);
PRx=random.nextInt(100);
}
while (PRy>=PLy){
PLy=(int)(Math.random()*100);
PRy=(int)(Math.random()*100);
}
}
void show(){
System.out.print("PL:("+PLx+","+PLy+")");
System.out.println("PR:("+PRx+","+PRy+")");
}
/**
* 懒汉单例模式创建
*/
private static volatile Rectangle instance=null; //保证 instance 在所有线程中同步
public static synchronized Rectangle getRectangle()
{
//getInstance 方法前加同步
if(instance==null)
{
instance=new Rectangle();
}
return instance;
}
}
public class Compare {
public Compare(Rectangle r1, Rectangle r2){
if(r1.PRy<=r2.PLy&&r1.PLy>=r2.PRy&&r1.PRx>=r2.PLx&&r1.PLx<=r2.PRx){
System.out.println("true");
}
else {
System.out.println("false");
}
}
}
public class main {
public static void main(String[] args) {
Rectangle r2 = Rectangle.getRectangle();
r2.setvalues();
r2.show();
Rectangle r1=new Rectangle();
r1.setvalues();
r1.show();
new Compare(r1,r2);
}
}