使用 C++ 统计给定尺寸矩形内菱形的数量


给定一个长为高度 X 宽度 的矩形。该矩形在二维坐标系中表示,左下角位于点 (0,0)。因此,目标是在此矩形内统计所有满足以下条件的菱形的数量:

  • 菱形面积大于 0。

  • 菱形的对角线平行于 x 轴和 y 轴。

  • 菱形的所有角点都具有整数坐标。

让我们通过示例来理解

输入 - 长度=3 宽度=3

输出 - 给定尺寸矩形内可能的菱形数量为:4

解释 - 下图显示了一个高度=宽度=3 的矩形。我们还可以看到四个面积 > 0 且对角线平行于两个轴的菱形(也具有整数坐标):

First [ (1,0), (2,1), (1,2), (0,1) ]
Second [ (2,0), (3,1), (2,2), (1,1) ]
Third [ (2,1), (3,2), (2,3), (1,2) ]
Fourth [ (1,1), (2,1), (1,2), (0,1) ]

输入 - 长度=2 宽度=3

输出 - 给定尺寸矩形内可能的菱形数量为:2

解释 - 下图显示了一个高度=2 宽度=3 的矩形。我们还可以看到两个菱形在里面

下面程序中使用的算法如下

第一个非零面积且具有整数坐标的菱形将从右上角的 (2,2) 开始。从索引 i=j=2 开始遍历到 i<=length 和 j<=length。将 i 和 j 增加 2 以固定偶数长度(用于整数坐标)。具有这些对角线的菱形数量将为 (height-i+1)X(width-j+1)。

  • 将长度和宽度作为整数。

  • 函数 possible_rhombus(int length, int width) 获取矩形的尺寸并返回矩形内满足所有提及条件的菱形的数量。

  • 将初始计数设为 0。

  • 从 i=2 遍历到 i<=length,以及从 j=2 遍历到 j<=width。

  • 对于每个 i,j,取 temp_1=length-i+1 和 temp_2=width-j+1

  • 将 temp_1*temp_2 加到计数中。

  • 将 i 和 j 增加 2(用于整数坐标)。

  • 最后返回计数作为结果。

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
long long possible_rhombus(int height, int width){
   long long count = 0;
   for (int i = 2; i <= height; i += 2){
      for (int j = 2; j <= width; j += 2){
         int temp_1 = height - i + 1;
         int temp_2 = width - j + 1;
         count += temp_1 * temp_2;
      }
   }
   return count;
}
int main(){
   int height = 4, width = 4;
   cout<<"Count of number of rhombi possible inside a rectangle of given size are: "<<possible_rhombus(height, width);
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

Count of number of rhombi possible inside a rectangle of given size are: 16

更新于: 2020-12-01

144 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.