Determine the position of the third person on regular N sided polygon in C++?


In a N sided polygon if two children are standing on A and B vertex then we need to determine the vertex number where another person should stand so that there should be minimum number of jumps required by that person to reach A and B both.

Two conditions to note here are that the polygon vertices are numbered in a clockwise manner and we will always choose the least numbered vertex in case there are multiple answers.

The vertexPosition(int sides, int vertexA, int vertexB) takes the no. of sides of the polygon and the position of vertex A and B. The for loop starts from 1 and iterates till i is less than or equal to the number of sides. If i isn’t equal to vertexA and vertexB then the absolute difference between the i and vertex A and similarly between i and vertexB is calculated and saved to x and y respectively.

int vertexPosition(int N, int vertexA, int vertexB){
   int tempSum = INT_MAX;
   int sum = 0;
   int position = 0;
   for (int i = 1; i <= N; i++) {
      if (i != vertexA && i != vertexB){
         int x = abs(i - vertexA);
         int y = abs(i - vertexB);

Next we save the sum of x and y to the sum variable and check if the sum is less than tempSum. If it is less than tempSum then the current sum value is assigned to tempSum and the current index value gets assigned to position variable. We check if the new sum obtained is less than previous sum stored in tempSum or not in the if statement so that we return the closest position N could be from A and B. After the loop finish iterating the position is returned.

         sum = x + y;
         if (sum < tempSum){
            tempSum = sum;
            position = i;
         }
      }
   }
   return position;
}

Example

Let us look at the following implementation to determine the position of the third person on regular N sided polygon.

#include <iostream>
using namespace std;
int vertexPosition(int N, int vertexA, int vertexB){
   int tempSum = INT_MAX;
   int sum = 0;
   int position = 0;
   for (int i = 1; i <= N; i++) {
      if (i != vertexA && i != vertexB){
         int x = abs(i - vertexA);
         int y = abs(i - vertexB);
         sum = x + y;
         if (sum < tempSum){
            tempSum = sum;
            position = i;
         }
      }
   }
   return position;
}
int main(){
   int N = 6, vertexA = 2, vertexB = 4;
   cout << "The vertex on which N should stand = " << vertexPosition(N, vertexA, vertexB);
   return 0;
}

Output

The above code will produce the following output −

The vertex on which N should stand = 6

Updated on: 16-Jan-2021

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements