Number of Boomerangs
A boomerang is a tuple of points where the distance between the first and second points is the same as the distance between the first and third points.
Here’s a Python code that returns the number of boomerangs for a given set of points:
|
|
Explanation:
- Define a Distance Function: We create a function
distance
to calculate the squared distance between two points. We use squared distance to avoid using the square root, as the relative distances will remain the same. - Iterate Through Points: We iterate through each point and compute the distances between that point and all other points in the set.
- Count Distances: We use a dictionary
distance_count
to count how many times each squared distance occurs. - Calculate Boomerangs: For each unique distance, if there are
n
occurrences, there aren * (n - 1)
possible ways to choose the other two points for the boomerang. We sum this value for all distances. - Return the Result: Finally, we return the total count of boomerangs.
This solution has a time complexity of (O(n^2)), where (n) is the number of points.