Simple Program For Finding Symmetrical Point

The problem statement is as follows:

Given two points P and Q, output the symmetric point of point P about Q.

Input Format

The first line contains an integer T representing the number of test cases

Each test case is a line containing four space-separated integers Px Py Qx Qy representing the (x,y) coordinates of P and Q.

Constraints

1 ⩽ T ⩽15
−100 ⩽ x, y⩽100

Output Format

For each test case output x and y coordinates of the symmetric point (each point in a new line).

Sample Input

2
0 0 1 1
1 1 2 2

Sample Output

2 2
3 3

Point of Symmetry:

A point of symmetry is a point that represents a "center" of sorts for the figure. For any line that you draw through the point of symmetry, if this line crosses the figure on one side of the point, the line will also cross the figure on the other side of the point, and at exactly the same distance from the point

Source: Purple Math

Formula:

In Euclidean geometry, the inversion of a point X with respect to a point P is a point X* such that P is the midpoint of the line segment with endpoints X and X*. In other words, the vector from X to P is the same as the vector from P to X*.

The formula for the inversion in P is

x* = 2a−x

Source: Point reflection – Wikipedia

With that in hand, the formula to find the symmetric point of x coordinate is:

x' = 2Qx – Px

And for Y coordinate, it is:

y' = 2Qy – Py

The Solution:

test_cases = STDIN.readline().chomp.to_i
loop do
  co = STDIN.readline().split.map(&:to_i)
  print "#{2 * co[2] - co[0]} #{2* co[3] - co[1]}\n"
  test_cases = test_cases - 1
  break if test_cases == 0
end

Breakdown of the solution:

  • Read the number of test cases from STDIN as an integer
  • Loop over the test cases
  • Read the set of points for each test case, into an integer array called co (Short for coordinates)
  • Px = co[0], Py = co[1], Qx = co[2], Qy = co[3]
  • Based on the formula above, the solution translates to:
    • x' = 2 * co[2] – co[0]
    • y' = 2 * co[3] – co[1]
  • Since Hackerrank requires the output to be in a specific format, the print statement is modeled that way

That's it, folks! I'll be starting with a couple of Project Euler problems in the next posts.

Note: Solution files for this and any future Mathematics problems that I solve can be found here: Github: glnarayanan/Mathematics