Challenge 4: Calculate Distance Between Points

In this exercise, you have to implement a class called Point which can be used to calculate distance between two points in x-y plane.

Problem Statement

You have to implement a class called Point that represents a specific point in the x-y plane. It should contain the following:

  • fields:

    • x( integer type)

    • y( integer type)

  • methods:

    • default constructor that initializes the point at (0,0)(0, 0)

    • parameterized constructor that takes input x and y and initializes the point to the respective coordinates.

    • float distance(), a method which calculates the distance of the point (represented by the object) from the origin, i.e. (0,0)(0, 0)

    • float distance(int x1, int y1), a method which calculates the distance between the point represented by the class object and (x1,y1)(x1, y1)

The distance between two points (x,y)(x, y) and (x1,y1)(x1, y1) can be calculated by the following formula:

distance=(x1x)2+(y1y)2\text{distance} = \sqrt{(x_1 - x)^2 + (y_1 - y)^2}

Sample Input

    Point p1 = Point(5, 5);
    

Sample Output

    p1.distance()  => 7.071
    p1.distance(2, 1)  => 5.0

Coding Exercise

First, take a close look and design a step-by-step algorithm before jumping to the implementation. This problem is designed for your practice, so initially try to solve it on your own. If you get stuck, you can always refer to the solution provided in the solution review.

Good Luck!

Get hands-on with 1400+ tech skills courses.