問題
Compute the Euclidean distance between (x1, y1) and (x2, y2): the square root of (x2 − x1)² + (y2 − y1)².
Implement distance(x1, y1, x2, y2).
Input
x1: First point x. y1: First point y. x2: Second point x. y2: Second point y.
Output
Return the distance.
制約
-1,000,000 ≤ each coordinate ≤ 1,000,000
例
入力:
x1 = 0.0
y1 = 0.0
x2 = 3.0
y2 = 4.0
期待される出力:
expected = 5.0
入力:
double x1 = 0.0;
double y1 = 0.0;
double x2 = 3.0;
double y2 = 4.0;
期待される出力:
double expected = 5.0;
入力:
double x1 = 0.0;
double y1 = 0.0;
double x2 = 3.0;
double y2 = 4.0;
期待される出力:
double expected = 5.0;
解説
√(3² + 4²) = √25 = 5.
入力:
x1 = 1.0
y1 = 1.0
x2 = 1.0
y2 = 1.0
期待される出力:
expected = 0.0
入力:
double x1 = 1.0;
double y1 = 1.0;
double x2 = 1.0;
double y2 = 1.0;
期待される出力:
double expected = 0.0;
入力:
double x1 = 1.0;
double y1 = 1.0;
double x2 = 1.0;
double y2 = 1.0;
期待される出力:
double expected = 0.0;
解説
Both points are the same, so the distance is 0.
解き方のヒント
まずは自分で考えてから、ヒントを1つずつ開いてみましょう。
ヒント 1
Compute the horizontal and vertical differences between the two points.
ヒント 2
Square both differences, add them, then take the square root of the total.
ヒント 3
Watch for negative coordinates, but the distance formula still works the same.
目安の計算量
O(1) time, O(1) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。