【问题标题】:How to find a common area inside squares如何在正方形内找到公共区域
【发布时间】:2022-01-16 05:43:20
【问题描述】:

我们如何找到 n 个正方形内部的交点,这些正方形的边平行于 xy 轴,给定它们的中心和边长?

输入是正方形的数量,然后是正方形的许多描述。每个正方形的描述是它的中心和边长的 x 和 y 坐标。例如:

3 5 11 10 7 9 10 10 6 8

描述三个正方形,从一个以 (5, 11) 为中心,边长为 10 的正方形开始。

【问题讨论】:

  • 查找两个正方形的交集。
  • 首先找到前两个的交集。那将是一个矩形。然后找到上一个交点和下一个正方形的交点。
  • @klutt:从技术上讲,这将找到正方形内部的交点(所有正方形内的区域),而不是正方形的交点(构成方格)。这可能是OP想要的,在这种情况下应该澄清问题和标题。 (这样想:如果有人让你在纸上画一个正方形,你是画一个实心黑框还是只画四条线?)
  • @EricPostpischil 啊,那是真的

标签: arrays c


【解决方案1】:

求正方形内部交点的算法(边平行于 xy 轴)由它们的中心和长度给出:

  • 将第一个正方形的中心(点(xy))和长度(l)转换为左边缘(x-l/2)和右边缘(x+l坐标/em>/2) 和底边的 y 坐标 (yl/2) 和顶边 ( >y+l/2)。将它们保留为 leftrightbottomtop
  • 对于以下每个正方形:
    • 将其中心和长度转换为上述坐标。
    • 找出哪个 x 坐标更大,旧的 left 或新的左边缘,并将其保留为新的 left
    • 找出哪个 x 坐标较小,旧的 right 或新的右边缘,并将其保留为新的 right
    • 找出哪个 y 坐标更大,旧的 bottom 或新的底边,并将其保留为新的 bottom
    • 找出哪个 y 坐标较小,旧的 top 或新的顶边,并将其保留为新的 top

处理完所有正方形后,leftrightbottomtop为矩形的坐标限定所有正方形内的区域。 (如果 right left 或 top bottom,则交集为空。否则,如果 right = left or top = bottom,交点是一条线[如果只有一个为真]或一个点[如果两者都是是真的]。)

【讨论】:

    【解决方案2】:

    这是一个计算两个矩形相交的简单函数。正方形是长方形,所以它可以用于正方形。我假设矩形的高度和宽度平行于 y 和 x 轴。

    struct point { double x, y; };
    struct rectangle { struct point a, b; };
    double max(double a, double b) { return a>b ? a : b; }
    double min(double a, double b) { return a<b ? a : b; }
    
    // Calculate the intersection of r1 and r2 and store the result in output
    // Assumes that a.x < b.x and a.y < b.y for r1 and r2
    // Returns NULL if there is no intersection 
    // Will always modify output. Do do NOT read output if this function returns NULL
    struct rectangle *intersection(
        struct rectangle *output, 
        const struct rectangle *r1, 
        const struct rectangle *r2) 
    {
        
        output->a.x = max(r1->a.x, r2->a.x);
        output->b.x = min(r1->b.x, r2->b.x);
        if(output->a.x > output->b.x) return NULL;
    
        output->a.y = max(r1->a.y, r2->a.y);
        output->b.y = min(r1->b.y, r2->b.y);
        if(output->a.y > output->b.y) return NULL;
    
        return output;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      相关资源
      最近更新 更多