View Problem

Find the distance between two points

DiskEdit
python
# problem description doesn't say 2D points ;)
from math import sqrt
print sqrt(sum((x-y)**2 for x,y in zip(a, b)))
DiskEdit
python
from math import hypot
print hypot(x2-x1, y2-y1)
DiskEdit
clojure
(defstruct point :x :y)

(defn distance
"Euclidean distance between 2 points"
[p1 p2]
(Math/pow (+ (Math/pow (- (:x p1) (:x p2)) 2)
(Math/pow (- (:y p1) (:y p2)) 2))
0.5))

(distance (struct point 0 0) (struct point 1 1)) ; => 1.4142135623730951
DiskEdit
clojure
(defn distance
"Euclidean distance between 2 points"
[[x1 y1] [x2 y2]]
(Math/sqrt
(+ (Math/pow (- x1 x2) 2)
(Math/pow (- y1 y2) 2))))

(distance [2 2] [3 3])
ExpandDiskEdit
fsharp
let distance' = distance (34, 78) (67, -45)
printfn "%3.2f" distance'
ExpandDiskEdit
fantom
px1 := 34.0f; py1 := 78.0f; px2 := 67.0f; py2 := -45.0f
distance := |Float x1, Float y1, Float x2, Float y2 -> Float|
{ ((x2-x1).pow(2.0f) + (y2-y1).pow(2.0f)).sqrt }

distance(px1, py1, px2, py2)
ExpandDiskEdit
erlang
Distance = distance({point, 34, 78}, {point, 67, -45}),
io:format("~.2f~n", [Distance]).
ExpandDiskEdit
erlang
Distance = distance(point:new(34, 78), point:new(67, -45)),
io:format("~.2f~n", [Distance]).
ExpandDiskEdit
go
import "fmt"
import "math"

type Point struct {
x, y float64
}

func (p Point) distance(other Point) (float64) {
dx := p.x - other.x
dy := p.y - other.y
return math.Sqrt(dx * dx + dy * dy)
}

func main() {
origin := Point{ 0, 0 }
point := Point{ 1, 1 }

fmt.Println(point.distance(origin))
}

Submit a new solution for python, clojure, fsharp, fantom ...
There are 17 other solutions in additional languages (cpp, csharp, groovy, haskell ...)