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

Comparing array members with nest loop,counting how many times the condition(if) was met

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

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;
   }