Find the coordinates of the fourth vertex of a square with given 3 vertices using XOR
Last Updated :
07 Dec, 2023
Given the coordinates of three points in a plane, find the coordinates of the fourth point that forms a square, suppose take the first vertex as (x1, y1), the second vertex as (x2, y2), the third vertex as (x3, y3) and find the fourth vertex (x4, y4).
Examples:
Input: p1 = { 20, 10 }, p2 = { 10, 20 }, p3 = { 20, 20 }
Output: the fourth point is: {10, 10}
Explanation:
Example-1
Input: p1 = {25, 24}, p2 = {10, 16}, p3 = {10, 24}
Output: the fourth point is: {25, 16}
Approach: To solve the problem using XOR follow the below steps:
- XOR of the same number gives a result of zero.
- In the same case. A square has four coordinates if we XOR all coordinates we get a result of zero.
- we have given three coordinates if we XOR these three coordinates we will get the fourth coordinates.
- XOR all x coordinates we get the x coordinate of a fourth point.
- XOR all y coordinates we get the y coordinate of a fourth point.
Below is the implementation for the above aprpoach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Point {
int x, y;
};
int main()
{
Point p1 = { 20, 10 }, p2 = { 10, 20 }, p3 = { 20, 20 };
int X = (p1.x ^ p2.x ^ p3.x);
int Y = (p1.y ^ p2.y ^ p3.y);
cout << "fouth point is : "
<< "{ " << X << ", " << Y << " }" << endl;
return 0;
}
|
Java
import java.io.*;
public class GFG {
static class Point {
int x, y;
public Point( int x, int y)
{
this .x = x;
this .y = y;
}
};
public static void main(String[] args)
{
Point p1 = new Point( 20 , 10 ),
p2 = new Point( 10 , 20 ),
p3 = new Point( 20 , 20 );
int X = (p1.x ^ p2.x ^ p3.x);
int Y = (p1.y ^ p2.y ^ p3.y);
System.out.println("fourth point is : { " + X + ", "
+ Y + " }");
}
}
|
Python3
class Point:
def __init__( self , x, y):
self .x = x
self .y = y
p1 = Point( 20 , 10 )
p2 = Point( 10 , 20 )
p3 = Point( 20 , 20 )
X = p1.x ^ p2.x ^ p3.x
Y = p1.y ^ p2.y ^ p3.y
print (f"Fourth point is : {{ {X}, {Y} }}")
|
C#
using System;
struct Point
{
public int x, y;
}
class Program
{
static void Main()
{
Point p1 = new Point { x = 20, y = 10 };
Point p2 = new Point { x = 10, y = 20 };
Point p3 = new Point { x = 20, y = 20 };
int X = (p1.x ^ p2.x ^ p3.x);
int Y = (p1.y ^ p2.y ^ p3.y);
Console.WriteLine( "Fourth point is: { " + X + ", " + Y + " }" );
}
}
|
Javascript
class Point {
constructor(x, y) {
this .x = x;
this .y = y;
}
}
function findFourthPoint(p1, p2, p3) {
const X = p1.x ^ p2.x ^ p3.x;
const Y = p1.y ^ p2.y ^ p3.y;
console.log( "fourth point is : { " + X + ", " + Y + " }" );
}
const p1 = new Point(20, 10);
const p2 = new Point(10, 20);
const p3 = new Point(20, 20);
findFourthPoint(p1, p2, p3);
|
Output
fouth point is : { 10, 10 }
Time Complexity : O(1)
Auxiliary Space : O(1)
Share your thoughts in the comments
Please Login to comment...