[SQL] HackerRank: Manhattan and Euclidean Distance

Eun LeeEun Lee
2 min read

Questions

https://www.hackerrank.com/challenges/weather-observation-station-18/problem?isFullScreen=true

http://hackerrank.com/challenges/weather-observation-station-19/problem?isFullScreen=true

Those two questions are pretty interesting. While researching distance measurement, I came across some fascinating articles that explain how it can be used not only for measuring actual distances on a map but also in Machine Learning.

Today I've Learned

Distance

  1. Manhattan Distanc

    Distance ​= ∣x2​−x1​∣+∣y2​−y1​∣

Manhattan distance calculates the total horizontal and vertical distances between two points. Essentially, it measures the distance traveled as if moving through city blocks, following a grid-like path instead of taking a direct route.

This method is particularly useful for finding paths in grid-based systems.

  1. Euclidean Distance

    Distance^2=(x2​−x1​)^2+(y2​−y1​)^2

Euclidean distance represents the direct, straight-line distance between two points, mathematically derived from the Pythagorean theorem.

It is typically applied when calculating the most direct path between two locations.

The fundamental difference between these methods lies in their approach: Manhattan distance exclusively considers horizontal and vertical movements, while Euclidean distance measures the shortest possible route. This distinctive characteristic makes Manhattan distance more appropriate for representing travel distances in urban environments with structured road networks.

These Systems Can be Used in

  1. Logistics: Used by courier companies or delivery services to optimize delivery routes.

  2. Planning: Used to analyze urban road networks and traffic flow, as well as calculate urban development directions.

  3. Machine Learning: Used to measure distances between objects or extract features in image processing.

  4. Game: Used to calculate movement paths for characters or NPCs in games or for collision detection.


New Function

  1. power : Calculates the value of the first argument raised to the power of the second argument.
SELECT POWER(Value, 2) AS square_value 
FROM Tables;
  1. sqrt : Returns the square root.
SELECT SQRT(Value) AS square_root_value
FROM Tables;
0
Subscribe to my newsletter

Read articles from Eun Lee directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Eun Lee
Eun Lee