-2

我需要生成一组唯一坐标 (A1, B1) 和 (A2, B2),它们的值介于 0 和 1 之间。这组唯一坐标不能位于现有坐标集 ([x1], [y1] ) 和 ([x2], [y2]) 由 sql 查询返回。如何使用 C# 编写一个脚本,该脚本生成的坐标是 1) 不在查询返回的值之间且 2) 不等于查询返回的值?

这里的逻辑基本上是用来在一个页面上绘制一组框。我需要绘制具有唯一坐标的新框,但这些新框不能重叠或位于现有框内。任何帮助是极大的赞赏!

4

2 回答 2

0

Assuming the existence of a Random, named randomizer for convenience, you could do...

do
{
A1 = randomizer.NextDouble();
B1 = randomizer.NextDouble();
} while(!((A1>=X1&&A1<=X2&&B1>=Y1&&B1<=Y2)||(A1>=X2&&A1<=X1&&B1>=Y2&&B1<=Y1)) //not inside other rectangle

do
{
A2 = randomizer.NextDouble();
B2 = randomizer.NextDouble();
}
while(!((A1==A2&&B1==B2)||  //not equal to other random coordinate
(A2>=X1&&A2<=X2&&B2>=Y1&&B2<=Y2)||
(A2>=X2&&A2<=X1&&B2>=Y2&&B2<=Y1)|| //not inside other rectangle
(A1<=X1&&A2>=X2&&B1<=Y1&&B2>=Y2)||
(A1<=X2&&A2>=X1&&B1<=Y2&&B2>=Y1)||
(A2<=X1&&A1>=X2&&B2<=Y1&&B1>=Y2)||
(A2<=X2&&A1>=X1&&B2<=Y2&&B1>=Y1)||)) //not containing other rectangle

It's a bit(read: very very) cludgy (I'm kinda embarassed about it actually), but it should work, and generate all possible random rectangles... eventually.

于 2012-08-31T19:06:52.880 回答
0

这适用于大约 99.99% 左右......

    void GenerateTest()
    {
        float x1, y1;
        float x2, y2;
         // fill x1,y1,x2,y2

        var r = new Random();
        Func<float> next = () => (float)r.NextDouble();

        var NotMatchingRect = RectangleF.FromLTRB(x1,y1,x2,y2);
        var Coordinates = Enumerable.Range(0, 1000).Select(i => new PointF(next(), next())).Where(p => !NotMatchingRect.Contains(p)).Distinct().Take(2).ToArray();
        if (Coordinates.Length != 2)
            throw new IndexOutOfRangeException();
    }
于 2012-08-31T18:43:30.330 回答