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


In this tutorial, we are going to learn how to find the position of a third person on a regular N-sided polygon.

We have given a regular N-sided polygon. And there are two persons on two different points already. Our task is to find the third point to place the third person such that the distance between the first two persons and the third person is minimized.

Let's see the steps to solve the problem.

  • Initialize the N and two points A and B.

  • Initialize the position of the third person, and the minimum sum to find the position.

  • Iterate from 1 to N.

    • If the current position is A or B, then skip it.

    • Find the sum of the absolute difference between the current position and A, B.

    • Compare it with the minimum sum.

    • If the current sum is less than the minimum sum, then update the position and minimum sum.

  • Print the position of the third person.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findThirdPersonStandingVertex(int N, int A, int B) {
   int position = 0;
   int minimum_sum = INT_MAX, sum;
   for (int i = 1; i <= N; i++) {
      // skipping the predefined vertices
      if (i == A || i == B) {
         continue;
      }
      else {
         // length between the current vertext to A and B
         sum = abs(i - A) + abs(i - B);
         // checking whether the current sum is less than previous sum
         if (sum < minimum_sum) {
            // updating the minimum sum and position of vertext
            minimum_sum = sum;
            position = i;
         }
      }
   }
   return position;
}
int main() {
   int N = 7, A = 5, B = 7;
   cout << "Vertex: " << findThirdPersonStandingVertex(N, A, B) << endl;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

Vertex: 6

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 27-Jan-2021

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements