c++ - 比较数组成员与嵌套循环,计算满足条件(if)的次数

标签 c++ arrays if-statement compare nested-loops

我正在比较三个不同的数组,在我的例子中,我的程序正在检查一个特定的圆与多少个其他圆相交。我的功能是这样做的:

void Intersection(int n, int A[], int B[], int C[]) 
{
ofstream out(rez);
   for (int i = 0; i < n; i++)
     {
       times_condition_met=0;
         for (int j = 0; j < n; j++)
         {
             if (Distance(X, Y, i, j) < (Radius[i] + Radius[j]))
             {
                 times_condition_met++;
             } 
         }
     }
}

我在三个不同的数组中有圆心和半径的坐标。

 X[] Y[] and R[]

这是必须满足的条件

if (Distance(X, Y, i, j) < (Radius[i] + Radius[j]))
            times_condition_met++;

Distance 函数计算两点之间(圆心之间)的距离。

我在计算一个特定圆圈与多少个其他圆圈相交时遇到的问题是,当我的函数正在检查是否满足条件时,例如如果 Circle1Circle2 times_condition_met++ 相交,然后一段时间后循环检查 Circle2 是否与 Circle1< 相交 它再次执行 times_condition_met++。那么我应该使用什么样的 if 以便 Circle1Circle2 相交并且 Circle2Circle1< 相交 会被计为条件只满足一次而不是两次?

最佳答案

我认为需要更新的是您的 for 循环。

尝试:

   for (int i = 0; i < n-1; i++)   // Update here
     {
       times_condition_met=0;
         for (int j = i+1; j < n; j++) // Update here

通过这种方式,您只会比较两个特定的圈子一次。

在第一个循环中,圆圈 0 将与圆圈 1,2,..,n-1 进行比较

在第二个循环中,圆圈 1 将与圆圈 2,3,..,n-1 进行比较

在第三个循环中,圆圈 2 将与圆圈 3,4,..,n-1 进行比较

等等……

在最后一个循环中,第 n-2 圈将与第 n-1 圈进行比较

全部在一起 - 任何一对圆圈只检查一次。

要计算哪个圆与大多数圆相交,您可以这样做:

   // Make a vector with n elements - all initialized to zero
   std::vector hitcounter(n, 0); 

   for (int i = 0; i < n-1; i++)
   {
        times_condition_met=0;
        for (int j = i+1; j < n; j++)
        {
             if (Distance(X, Y, i, j) < (Radius[i] + Radius[j]))
             {
                 times_condition_met++;

                 // increment hit counter
                 hitcounter[i] = hitcounter[i] + 1;
                 hitcounter[j] = hitcounter[j] + 1;
             } 
        }
   }

   int top = -1;
   int topIndex = -1;
   for (int i = 0; i < n; i++)
   {
       if (hitcounter[i] > top)
       {
           top = hitcounter[i];
           topIndex = i;
       }
   }

   if (top == -1)
   {
       cout << "No intersect found" << endl;
   }
   else
   {
       cout << "Most intersect found for circle " << topIndex << " Hits=" << top << endl;
   }

关于c++ - 比较数组成员与嵌套循环,计算满足条件(if)的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34072981/

相关文章:

java - 如何检查字符串中的值?

c++ - 使 eclipse 解析或忽略 CUDA 内核启动参数

c++ - API 更改时函数参数的常量正确性

C++ 转换字节

javascript - 使用单个循环仅添加数组的不同元素

if-statement - gnuplot 的 if block 中的 Shell 命令

python - 在 Python 中跳过代码行?

c++ - 如何在编译时从类型创建静态字符串

c++ - 用 C++ 编码时,你能在 visual studio 中删除 stdafx.h 吗?

c++ - 字符数组的Initializer-String太长