28
\$\begingroup\$

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!

\$\endgroup\$
8
  • 17
    \$\begingroup\$ I'll give brainfuck a shot. Let's see what horrible monster comes out. \$\endgroup\$ Commented Jan 30, 2016 at 12:56
  • \$\begingroup\$ I assume you mean the Euclidean distance? \$\endgroup\$ Commented Jan 30, 2016 at 13:54
  • 3
    \$\begingroup\$ @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 :) \$\endgroup\$ Commented Jan 30, 2016 at 14:02
  • \$\begingroup\$ @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). \$\endgroup\$ Commented Jan 30, 2016 at 14:58
  • 2
    \$\begingroup\$ @DenkerAffe I think it's safe to say that brainfuck will never win a code golf. But it's just for fun anyways :) \$\endgroup\$ Commented Jan 30, 2016 at 16:17

48 Answers 48

1
2
1
\$\begingroup\$

Clojure, 48 bytes

#(Math/sqrt(apply +(for[d(map - % %2)](* d d)))) 
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 4 bytes

-nOt 

Try it online!

Negative not y'all!

- # a-b n # (a-b)**2 O # sum((a-b)**2) for all a,b t # sqrt(sum((a-b)**2) for all a,b) 
\$\endgroup\$
1
\$\begingroup\$

Elixir, 74 bytes

:math.sqrt Enum.reduce Enum.zip(p,q),0,fn({a,b},c)->:math.pow(a-b,2)+c end 

You can try it online

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! Nice first post! \$\endgroup\$ Commented Nov 24, 2017 at 2:15
1
\$\begingroup\$

TI-Basic (TI-84 Plus CE), 15 bytes

Prompt A,B √(sum((LA-LB)2

TI-Basic is a tokenized language.

Prompts for input as two lists, and returns the Euclidian distance betwrrn them in Ans

Explanation:

Prompt A,B # 5 bytes, Prompts for two inputs; if the user inputs lists: # they are stored in LA and LB √(sum((LA-LB)2 # 10 bytes, Euclidian distance between points #(square root of (sum of (squares of (differences of coordinates)))) 
\$\endgroup\$
1
\$\begingroup\$

Excel VBA, 36 Bytes

Anonymous VBE immediate window function that takes input as two vectors, which are projected unto the range 1:2, and outputs to the VBE immediate window

[3:3]="=(A1-A2)^2":?[Sqrt(Sum(3:3))] 
\$\endgroup\$
1
\$\begingroup\$

R, 4 bytes

dist 

This is a built-in function to calculate the distance matrix of any input matrix. Defaults to euclidean distance.

Example usage:

> x=matrix(c(1.5,-3.45,2,-13,-5,145),2) > x [,1] [,2] [,3] [1,] 1.50 2 -5 [2,] -3.45 -13 145 > dist(x) 1 2 150.8294 

If you're feeling disappointed because it's a built-in, then here's a non-built-in (or at least, it's less built-in...) version for 22 bytes (with thanks to Giuseppe):

pryr::f(norm(x-y,"F")) 

This is an anonymous function that takes two vectors as input.

\$\endgroup\$
1
  • \$\begingroup\$ function(x,y)norm(x-y,"F") is shorter than your second version. \$\endgroup\$ Commented Apr 11, 2018 at 15:56
1
\$\begingroup\$

Python 3, 44 bytes

lambda*a:sum((x-y)**2for x,y in zip(*a))**.5 

Try it online!

Ungolfed version:

 ₙ sqrt( ∑(xᵢ - yᵢ)² ) ⁱ⁼¹ def d(a, b): # two points (lists or tuples) return sum( # sum of... (x - y) ** 2 # (xᵢ - yᵢ)² for x,y in zip(a, b) # ) ** 0.5 # square root of sum 
\$\endgroup\$
1
\$\begingroup\$

Stax, 8 bytes

äÖ╙í▼=╬b 

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

\ zip the coordinates into pairs { for each pair, :s compute the absolute span J+ square and add to total F |Q square root result 

Run this one

\$\endgroup\$
1
\$\begingroup\$

Factor + math.distances, 18 bytes

euclidian-distance 

Try it online!

Built-in.

\$\endgroup\$
1
\$\begingroup\$

Husk, 6 bytes

√Σzo□- 

Try it online!

Explanation

√Σzo□- z zip input arguments o with composed function - difference □ squared Σ sum √ sqrt 
\$\endgroup\$
1
\$\begingroup\$

Fortran (GFortran), 85 80 bytes

function d(A,n);real A(n,2);s=0;do5 i=1,n;s=s+(A(i,1)-A(i,2))**2 5 d=sqrt(s);end 

Try it online!   85 bytes

Instead of two vectors, I read all the data into two rows of array A. But Fortran 'helpfully' stores matrices by column so when I call the procedure A is transposed.
Using line number 5 instead of enddo saves 2 bytes :)
Saved 5 bytes using function instead of subroutine

\$\endgroup\$
1
  • \$\begingroup\$ If only the IMSL library was installed on TIO. I could have used the DISL2 function. \$\endgroup\$ Commented Mar 8, 2023 at 9:28
1
\$\begingroup\$

Swift 5.9, 86 bytes

import Foundation let f={(p:[(Double,_)])in sqrt(p.map{pow($0.1-$0.0,2)}.reduce(0,+))} 

Don't Try It Online, because TIO is too old. Here's a JDoodle link instead.

f is of type ([(Double, Double)]) -> Double -- it takes an array of pairs of coordinates, one per vector.

I just used the subtract-square-sum-squareRoot trick borrowed from other answers.

\$\endgroup\$
1
\$\begingroup\$

Go, 97 bytes

import."math" func f(p,q[]float64)(d float64){for i:=range p{d+=Pow(p[i]-q[i],2)} return Sqrt(d)} 

Attempt This Online!

\$\endgroup\$
0
\$\begingroup\$

Pyke, 7 bytes

,A-MXs, 

Try it here!

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

\$\endgroup\$
0
\$\begingroup\$

Ruby, 50 bytes

Zip, then map/reduce. Barely edges out the other Ruby answer from @LevelRiverSt by 2 bytes...

->p,q{p.zip(q).map{|a,b|(a-b)**2}.reduce(:+)**0.5} 

Try it online

\$\endgroup\$
0
\$\begingroup\$

C 276 bytes

f(){*a,*b,d=0;l=1;a=malloc(sizeof(float)*50);b=malloc(sizeof(float)*50);scanf("%f",&a[0]);while(getchar()!='\n'){scanf("%f",&a[l]);l++;}l=1;scanf("%f",&b[0]);while(getchar()!='\n'){scanf("%f",&b[l]);l++;}for(int i=0;i<l;i++){d+=pow((a[i]-b[i]),2);}printf("%.5f",pow(d,0.5));} 

Ungolfed version:

void f() { float *a,*b,d=0; int l=1; a=malloc(sizeof(float)*50); b=malloc(sizeof(float)*50); //Accept p1,p2,p3.....pn scanf("%f",&a[0]); while(getchar()!='\n') { scanf("%f",&a[l]); l++; } l=1; //Accept q1,q2,q3.....qn scanf("%f",&b[0]); while(getchar()!='\n') { scanf("%f",&b[l]); l++; } for(int i=0;i<l;i++) { d+=pow((a[i]-b[i]),2); } printf("\n%.5f",pow(d,0.5)); } 

Pretty straightforward. This solution lets you measure distance between 2 points in upto 50 dimensions (can be increased).

In Cartesian coordinates, input the position of first point of n dimensions. (p1 p2 p3 ...pn) and press Enter.

Next, input the position of second point of n dimensions. (q1 q2 q3 ...qn) and press Enter to get the Euclidean Distance.

\$\endgroup\$
0
\$\begingroup\$

J-uby, 35 bytes

+:zip|:*&(+:-|~:**&2)|:sum|~:**&0.5 

Attempt This Online!

+:zip | :* & (+:- | ~:** & 2) | :sum | ~:** & 0.5 +:zip | # Zip input arrays, then :* & ( ) # map with +:- | ~:** & 2 # Difference, then square | :sum | # then sum, then ~:** & 0.5 # square root 
\$\endgroup\$
0
\$\begingroup\$

Thunno 2, 4 bytes

-²Sƭ 

Try it online!

Explanation

-²Sƭ # Implicit input - # Subtract ² # Square S # Sum ƭ # Square root # Implicit output 
\$\endgroup\$
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.