Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Here is another simple one:

The Challenge

Given two points in an n-dimensional space, output the distance between them, also called the Euclidean distance.

  • The coordinates will be rational numbers; the only limits are the restrictions of your language.
  • Lowest dimension is 1, highest is whatever your language can handle
  • You may assume that the two points are of the same dimension and that there will be no empty input.
  • The distance has to be correct to at least 3 decimal places. If your language does not support floating point numbers, output the nearest whole number.

Rules

  • As usual, function or full program allowed.
  • Input may be taken from STDIN, command line- or function arguments.
  • Input format is up to you, specify which one you used in your answer.
  • Output may be provided by printing to stdout or return value.
  • This is so lowest byte-count wins! In case of a tie, the earlier answer wins.

Test cases

Each point is represented by a list of length n.

[1], [3] -> 2
[1,1], [1,1] -> 0
[1,2], [3,4] -> 2.82842712475
[1,2,3,4], [5,6,7,8] -> 8
[1.5,2,-5], [-3.45,-13,145] -> 150.829382085
[13.37,2,6,-7], [1.2,3.4,-5.6,7.89] -> 22.5020221314

Happy Coding!

share|improve this question
10  
I'll give brainfuck a shot. Let's see what horrible monster comes out. – YoYoYonnY Jan 30 at 12:56
    
I assume you mean the Euclidean distance? – flawr Jan 30 at 13:54
2  
@flawr Yep, exactly. Just wanted to keep the title simple, since not everyone might know what that is at first glance. Could definetly write that in the challange tho :) – DenkerAffe Jan 30 at 14:02
    
@DenkerAffe is it OK to return the distance squared if "your programming language does not support floating points"? This would make my brainfuck program a lot more accurate (Otherwise I'll have to implement some sort of estimation algorithm). – YoYoYonnY Jan 30 at 14:58
1  
@DenkerAffe I think it's safe to say that brainfuck will never win a code golf. But it's just for fun anyways :) – YoYoYonnY Jan 30 at 16:17

26 Answers 26

up vote 23 down vote accepted

MATL, 2 bytes

ZP

Try it online!

The ZP function (corresponding to MATLAB's pdist2) computes all pairwise distances between two sets of points, using Euclidean distance by default. Each set of points is a matrix, and each point is a row. In this case it produces a single result, which is the distance between the two points.

share|improve this answer
7  
No way this is real – Martijn Jan 30 at 19:06
4  
I'm patiently waiting for the inevitable single-byte MATL answer;) – Andras Deak Jan 30 at 20:18
2  
Ever heard those languages whereas the main point of the language is to solve obscure Code Golf problems? This sounds exactly like it. Makes me wonder if esoteric languages exist exactly for this. – MathManiac Jan 31 at 5:00
1  
This definitely puts the money where the mouth is. Nice job Luis! – rayryeng Jan 31 at 6:10
1  
The pdist2 function literally changed my life when I found it... – Lui Jan 31 at 9:08

MATL, 4.0 3 bytes

Thanks for -1 by @AndrasDeak!

-Zn

Reads two vectors (via implicit input that is requested by -) then substracts those and calculates the norm of their difference with Zn.

Try it Online!

share|improve this answer
10  
Please start upvoting tomorrow, I already motorboated today. – flawr Jan 30 at 14:25
3  
Too late...You gotta motorboat again :P – DenkerAffe Jan 30 at 16:47
1  
@DenkerAffe never trust a bounty hunter. – Andras Deak Jan 30 at 20:14
1  
Bounty hunters... we don't need that scum – Luis Mendo Jan 30 at 23:53
1  
@flawr How could you forget about pdist2? :-P – Luis Mendo Jan 31 at 3:30

Pyth, 3 bytes

.aQ

.a - L2 norm of vector difference of A[0] and A[1].

Literally a function that does this problem

Try it here.

share|improve this answer

Jelly, 4 bytes

_²S½

Try it online!

How it works

_²S½    Main link. Left input: A (list). Right input: B (list).

_       Subtract B from A, element by element.
 ²      Square all differences.
  S     Add all squares.
   ½    Take the square root of the sum.
share|improve this answer
1  
Yikes. Just 4 bytes with Jelly. I cannot see how anyone can do better than that. – CarpetPython Jan 30 at 13:17
4  
@CarpetPython Apparently MATL can... – DenkerAffe Jan 30 at 16:43
    
@CarpetPython And Pyth – isaacg Jan 31 at 5:12

Mathematica, 11 bytes

Norm[#-#2]&

Input as two lists, output as a number. If the input is exact (integers, rationals, etc.) the output will be exact as well. If the input contains a floating-point number, the output will be a float as well.

share|improve this answer
5  
EuclideanDistance would work nicely too... if the name weren't so darn long! If only there were "MATL for Mathematica" this would be a single byte =) – 2012rcampion Jan 31 at 1:18

Octave, 15 bytes

@(x,y)norm(x-y)

Example:

octave:1> d=@(x,y)norm(x-y);
octave:2> d([13.37,2,6,-7], [1.2,3.4,-5.6,7.89])
ans =  22.502
share|improve this answer

CJam, 11 8 bytes

Thanks to Dennis for saving 3 bytes.

q~.-:mhz

Run all test cases.

Explanation

q~   e# Read and evaluate input.
.-   e# Vectorised difference.
:mh  e# Reduce √(x²+y²) over the list.
z    e# Take abs() to handle 1D input.

See this tip for why :mh works.

share|improve this answer
    
That trick with :mh is very nice indeed – Luis Mendo Jan 30 at 16:57
    
@PeterTaylor every single time... Thanks. :) – Martin Büttner Jan 30 at 17:41

Haskell, 46 bytes

d :: Floating c => [c] -> [c] -> c
d a=sqrt.sum.map((^2).uncurry(flip(-))).zip a

Haskell, 35 bytes (By @nimi)

d :: Float c => [c] -> [c] -> c
d a=sqrt.sum.zipWith(((^2).).(-))a

Haskell, 31 bytes

Like this Scala answer, takes input as a sequence of tuples

<hack>

d :: Float c => [(c,c)] -> c
d=sqrt.sum.map$(^2).uncurry(-)

</hack>

Examples:

Prelude> d [1] [3]
2.0
Prelude> d [1,1] [1,1]
0.0
Prelude> d [1,2,3,4] [5,6,7,8]
8.0
Prelude> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
Prelude> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522
share|improve this answer
11  
uncurry ಠ_ಠ When cooking I sometimes wish to have an unsalt function. – flawr Jan 30 at 14:27
    
2  
map + uncurry + zip rarely pays off, use zipWith: d a=sqrt.sum.zipWith(((^2).).(-))a. – nimi Jan 30 at 21:16
1  
can't you save another couple of bytes by eta reduction? – jk. Feb 1 at 15:05
    
@jk. Not sure... I don't think so, since (.) always returns a function that takes only one argument... I think you can do something like (.).(.), but that isn't really worth it. – YoYoYonnY Feb 2 at 14:29

APL, 14 11 bytes

.5*⍨(+/-×-)

This is dyadic function train that takes the vectors on the left and right and returns the Euclidean norm of their difference.

Explanation:

       -×-)  ⍝ Squared differences
    (+/      ⍝ Sum them
.5*⍨         ⍝ Take the square root

Try it here

Saved 3 bytes thanks to Dennis!

share|improve this answer
    
.5*⍨(+/-×-) saves a few bytes. – Dennis Jan 30 at 19:14
3  
Can this really be the first time I've seen commented APL code? That symbol! I've always found the APL character set weird, but I never realized a dismembered zombie finger was the comment marker. ;-) – Level River St Jan 30 at 22:34
    
@steveverrill I <s>comment</s> put zombie fingers in just about all of my APL submissions here. ¯\_(ツ)_/¯ – Alex A. Jan 31 at 3:39
    
@Dennis Awesome, thanks! – Alex A. Jan 31 at 6:19
    
@AlexA. The poor alignment (due to the non-monospaced APL characters) happened to give it a particularly hand-like appearance this time. You've golfed it down from 4 lines to 3, and ruined the effect :-S This answer of yours has 4 lines, but doesn't have the hand-like appearance codegolf.stackexchange.com/a/70595/15599 Anyway, I like that you still have a single character smiley in your code. – Level River St Jan 31 at 8:39

Julia, 16 bytes

N(x,y)=norm(x-y)

This is a function that accepts two arrays and returns the Euclidean norm of their difference as a float.

You can verify all test cases at once online here.

share|improve this answer

golflua, 43 chars

\d(x,y)s=0~@i,v i(x)s=s+(v-y[i])^2$~M.q(s)$

Works by calling it as

> w(d({1,1},{1,1}))
0
> w(d({1,2},{3,4}))
2.82842712475
> w (d({1,2,3,4},{5,6,7,8}))
8


A Lua equivalent would be

function dist(x, y)
    s = 0
    for index,value in ipairs(x)
       s = s + (value - y[index])^2
    end
    return math.sqrt(s)
end
share|improve this answer

Seriously, 12 bytes

,iZ`i-ª`MΣ√A

Try it online!

Explanation:

,iZ`i-ª`MΣ√A
,iZ           get input, flatten, zip
   `   `M     map:
    i-ª         flatten, subtract, square
         Σ√A  sum, sqrt, abs
share|improve this answer

Python 2, 48 bytes

A straight forward solution. The function expects 2 points as sequences of numbers, and returns the distance between them.

lambda a,b:sum((d-e)**2for d,e in zip(a,b))**.5

Example:

>>> f([13.37,2,6,-7], [1.2,3.4,-5.6,7.89])
22.50202213135522
share|improve this answer

JavaScript ES7, 45 bytes

(a,b)=>a.reduce((s,v,i)=>s+(v-b[i])**2,0)**.5

Expects two arrays of equal length corresponding to the two N-dimensional vectors.

share|improve this answer
    
Please add an example on how to invoke this function including a specification of the input format, since this is not obvious on the first glance. – DenkerAffe Jan 30 at 16:41
    
@DenkerAffe Sorry, having overlooked that clause, I had just used the same format as the examples and indeed everyone previous to me at the time. – Neil Jan 30 at 17:07

Ruby, 52

->p,q{t=0;p.size.times{|i|t+=(p[i]-q[i])**2}
t**0.5}

In test program

f=->p,q{t=0;p.size.times{|i|t+=(p[i]-q[i])**2}
t**0.5}

p f[[1], [3]] # 2
p f[[1,1], [1,1]] # 0
p f[[1,2], [3,4]] # 2.82842712475
p f[[1,2,3,4], [5,6,7,8]] # 8
p f[[1.5,2,-5], [-3.45,-13,145]] # 150.829382085
p f[[13.37,2,6,-7], [1.2,3.4,-5.6,7.89]] # 22.5020221314
share|improve this answer

AppleScript, 241 239 bytes

This is golfed code, but I've put comments in in the form --.

on a()    -- Calling for getting input
set v to{1}          -- Arbitrary placeholder
repeat until v's item-1=""       -- Repeat until no input is gathered
set v to v&(display dialog""default answer"")'s text returned   -- Add input to list
end      -- End the repeat
end      -- End the method
set x to a()   -- Set the array inputs
set y to a()
set z to 0     -- Sum placeholder
set r to 2     -- 2 is the first significant array index
repeat(count of items in x)-2     -- Loop through all but first and last of the array
set z to z+(x's item r-y's item r)^2    -- Add the square of the difference
end   -- End the repeat
z^.5  -- Return the square root of the sum

This uses the same algorithm as most of the other programs here.

run sample

share|improve this answer

Java, 130 117 114 bytes

This is the obvious solution. I don't usually golf in Java, but I was curious to see if Java could beat the Brainfuck version. Doesn't seem like I did a good job then.. Maybe one could use the new Map/Reduce from Java 8 to save some bytes.

Thanks to @flawr (13 bytes) and @DarrelHoffman (3 bytes)!

Golfed:

public double d(float[]a,float[]b){float x=0,s;for(int i=-1;++i<a.length;s=a[i]-b[i],x+=s*s);return Math.sqrt(x);}

Ungolfed:

public static double d(float[]a,float[]b){
    float x=0,s;for(int i=-1;++i<a.length;s=a[i]-b[i],x+=s*s);
    return Math.sqrt(x);
}
share|improve this answer
2  
You can certainly shorten the function name to one character. The for loop be compressed to double x=0,s;for(int i=0;++i<a.length;s=a[i]-b[i],x+=s*s); – flawr Jan 31 at 0:28
    
You can use int instead of double to save characters too, and declare i next to x. – Rodolvertice Jan 31 at 0:49
1  
This is way oversized. See flawr's suggestion for the loop. Using Java 8 lambda, this can be reduced to: double[]a,b->{double x=0,s;for(int i=0;++i<a.length;s=a[i]-b[i],x+=s*s);return Math.sqrt(x);} for a total of 93 bytes. – VTCAKAVSMoACE Jan 31 at 14:04
    
I totally forgot to shorten the function name.. @flawr thanks a lot for those tips, I didn't know you could do that. – Bruce_Forte Jan 31 at 17:12
    
If you don't care too much about precision, you can replace three of the doubles with floats and save 3 bytes. (You can't change the return type, because Math.sqrt() returns a double, and you'd have to add a cast.) It's not much of a savings, but 3 bytes is enough to beat the BF solution right now... Also, it's not necessary to initialize x to 0, Java variables start at 0 automatically, so -2 more bytes there. – Darrel Hoffman Jan 31 at 18:58

Perl 6, 30 29 26 24 bytes

{sqrt [+] ([Z-] $_)»²}

(Thanks @b2gills for 2 more bytes lost)

usage

my &f = {sqrt [+] (@^a Z-@^b)»²};

say f([1], [3]); # 2
say f([1,1], [1,1]); # 0
say f([1,2], [3,4]); # 2.82842712474619
say f([1,2,3,4], [5,6,7,8]); # 8
say f([1.5,2,-5], [-3.45,-13,145]); # 150.829382084526
say f([13.37,2,6,-7], [1.2,3.4,-5.6,7.89]); # 22.5020221313552
share|improve this answer
    
{sqrt [+] ([Z-] $_)»²} – Brad Gilbert b2gills Feb 5 at 6:28

J, 9 bytes

+&.*:/-/>

This is a function that takes one set of coordinates from the other (-/>), and then performs a sum + under &. square *:.

The input should be in the format x y z;a b c where x y z is your first set of co-ordinates and a b c is the other.

share|improve this answer

𝔼𝕊𝕄𝕚𝕟, 6 chars / 13 bytes

МŰМŷ…ï

Try it here (Firefox only).

Calculates norm of difference of input arrays.

share|improve this answer

Scala, 67 62 bytes

def e(a:(Int,Int)*)=math.sqrt(a map(x=>x._2-x._1)map(x=>x*x)sum)

Requires input as a sequence/vector of var-arg tuples
Example:

scala> e((1, 5), (2, 6), (3, 7), (4, 8))
res1: Double = 8.0
share|improve this answer

C#, 72 bytes

(float[]i,float[]n)=>System.Math.Sqrt(i.Zip(n,(x,y)=>(x-y)*(x-y)).Sum())

A simple solution using Linq.

share|improve this answer

Python 3, 70 Chars

Loops through, finding the square of the difference and then the root of the sum:

a=input()
b=input()
x=sum([(a[i]-b[i])**2 for i in range(len(a))])**.5
share|improve this answer
2  
Drop a few more: sum([(x-y)**2 for x,y in zip(a,b)])**.5 – Benjamin Jan 31 at 4:55

Sage, 35 bytes

lambda a,b,v=vector:norm(v(a)-v(b))

This function takes 2 lists as input and returns a symbolic expression. The distance is calculated by performing vector subtraction on the lists and computing the Euclidean norm of the resultant vector.

Try it online

share|improve this answer

Mathcad, bytes

enter image description here

Uses the built-in vector magnitude (absolute value) operator to calculate the size of the difference between the two points (expressed as vectors).


Mathcad golf size on hold until I get (or somebody else gets) round to opening up the discussion on meta. However, the shortest way (assuming that input of the point vectors doesn't contribute to the score) is 3 "bytes" , with 14 bytes for the functional version.

share|improve this answer

Pyke, 7 bytes

,A-MXs,

Try it here!

Transpose, apply subtract, map square, sum, sqrt.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.