如何用三个重叠的形状来解决这个逻辑命题



我需要在while(...)中写条件,其中所有三个形状将重叠,然后在while循环中使用,试图找到形状的坐标组合,这将不会重叠其他形状。我在代码中有3个while循环-每个循环用于选择特定形状的坐标对。

此代码冻结程序:

                    xRing = (int) ((getWidth() - ringSize) * (Math.random()));
                yRing = (int) ((getHeight() - ringSize) * (Math.random()));
                while( !( 
                           (xSquare + squareSize) < (xRing)
                        || (xSquare) > (xRing + ringSize )
                        || (ySquare + squareSize) < (yRing)
                        || (ySquare) > (yRing + ringSize)
                        )
                        ||
                        !( 
                           (xSquare2 + square2Size) < (xRing)
                        || (xSquare2) > (xRing + ringSize )
                        || (ySquare2 + square2Size) < (yRing)
                        || (ySquare2) > (yRing + ringSize)
                        )
                        ||
                        !( 
                           (xSquare + squareSize) < (xSquare2)
                            || (xSquare) > (ySquare2 + square2Size )
                            || (ySquare + squareSize) < (ySquare2)
                            || (ySquare) > (ySquare2 + square2Size)
                        )
                    ){
                    xRing = (int) ((getWidth() - ringSize) * (Math.random()));
                    yRing = (int) ((getHeight() - ringSize) * (Math.random()));

                }

,这可以工作,但允许重叠Square和Square2:

        while( !( 
                           (xSquare + squareSize) < (xRing)
                        || (xSquare) > (xRing + ringSize )
                        || (ySquare + squareSize) < (yRing)
                        || (ySquare) > (yRing + ringSize)
                        )
                        ||
                        !( 
                           (xSquare2 + square2Size) < (xRing)
                        || (xSquare2) > (xRing + ringSize )
                        || (ySquare2 + square2Size) < (yRing)
                        || (ySquare2) > (yRing + ringSize)
                        )

据我所知,我必须检查每对是否有重叠,有3种形状,3种可能的重叠。正如我之前提到的我的代码逻辑,我可以检查重叠的2对。当我添加第三个条件时,检查-它无法退出while。所有的逻辑在我看来都是完全正确的。我的循环将退出,如果它找到第一个坐标,其中三个形状不可能重叠。

实际上我的简短版本的代码应该是这样的:

while( not(ring NOT overlaps square 1) or 
       not(ring NOT overlaps square 2) or 
       not(square 1 NOT overlaps square 2) ) {
  ...
}

解决:在绘制每个形状时,我应该检查2组合(而不是3),所以对于每个while(),我必须有不同的条件

你基本上是在检查矩形中的随机位置,如果它们都包含在至少两个形状中(假设你的条件是正确的,我没有检查),你的循环将不会退出。

最好循环遍历矩形中的所有像素并检查它们。这样,循环将在检查完所有像素后停止。

至于你的条件:我没有彻底检查过,但由于你使用了很多条件,我假设至少有一个外部条件是真的,因此循环不会停止。

我认为你的3个顶级条件应该是这样的:

while( not(ring overlaps square 1) or 
       not(ring overlaps square 2) or 
       not(square 1 overlaps square 2) ) {
  ...
}

例如,如果正方形1和2不重叠,则条件将始终为真,循环将永远运行。

最新更新