Distance between two points in n-dimensional space

22

4

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!

Denker

Posted 2016-01-30T12:50:41.727

Reputation: 6 639

16I'll give brainfuck a shot. Let's see what horrible monster comes out. – YoYoYonnY – 2016-01-30T12:56:14.483

I assume you mean the Euclidean distance? – flawr – 2016-01-30T13:54:06.580

3@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 :) – Denker – 2016-01-30T14:02:25.760

@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 – 2016-01-30T14:58:06.307

@YoYoYonnY Go for it then. Brainfuck won't win this one anyway, but I really wanna see your solution :) Just make it clear in your answer that you output the distance squared. – Denker – 2016-01-30T15:31:27.027

2@DenkerAffe I think it's safe to say that brainfuck will never win a code golf. But it's just for fun anyways :) – YoYoYonnY – 2016-01-30T16:17:04.753

I propose adding a non-floating point clause (See my edit) – YoYoYonnY – 2016-01-31T00:46:37.257

Can we assume the input is all in floating-point (no ints) if our language supports it/is strongly-typed? – snail_ – 2018-04-11T21:25:26.663

Answers

26

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.

Luis Mendo

Posted 2016-01-30T12:50:41.727

Reputation: 87 464

7No way this is real – Martijn – 2016-01-30T19:06:37.297

6I'm patiently waiting for the inevitable single-byte MATL answer;) – Andras Deak – 2016-01-30T20:18:31.913

2Ever 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. – Lawful Lazy – 2016-01-31T05:00:50.143

1This definitely puts the money where the mouth is. Nice job Luis! – rayryeng - Reinstate Monica – 2016-01-31T06:10:34.713

1The pdist2 function literally changed my life when I found it... – Lui – 2016-01-31T09:08:44.123

15

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!

flawr

Posted 2016-01-30T12:50:41.727

Reputation: 40 560

10Please start upvoting tomorrow, I already motorboated today. – flawr – 2016-01-30T14:25:48.860

3Too late...You gotta motorboat again :P – Denker – 2016-01-30T16:47:40.500

1

Save some upvotes for me :-P

– Luis Mendo – 2016-01-30T18:48:44.207

@LuisMendo dat shameless advertising :O – Denker – 2016-01-30T20:04:15.193

1@DenkerAffe never trust a bounty hunter. – Andras Deak – 2016-01-30T20:14:34.117

1Bounty hunters... we don't need that scum – Luis Mendo – 2016-01-30T23:53:18.877

@LuisMendo I'm not sure yet whether I should flag your self promotion as rude or offensive, not constructive or too chatty :D – flawr – 2016-01-31T00:55:58.350

PS: You can start to upvote now! – flawr – 2016-01-31T00:56:28.930

@flawr way ahead of you;) – Andras Deak – 2016-01-31T01:48:11.967

1@flawr How could you forget about pdist2? :-P – Luis Mendo – 2016-01-31T03:30:45.893

@LuisMendo Because I only knew about pdist but not about pdist2. Only a noob would make a second function with the same name again with an appended 2... Staring at you MATLAB. – flawr – 2016-01-31T10:37:22.800

1quietly leaves and posts a challenge that's solved with two-dimensional convolution – Luis Mendo – 2016-01-31T12:26:57.663

Where is that challenge? – flawr – 2016-01-31T17:46:14.383

12

Pyth, 2 bytes

.a

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

Literally a function that does this problem

Try it here.

Blue

Posted 2016-01-30T12:50:41.727

Reputation: 26 661

10

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.

Dennis

Posted 2016-01-30T12:50:41.727

Reputation: 196 637

1Yikes. Just 4 bytes with Jelly. I cannot see how anyone can do better than that. – Logic Knight – 2016-01-30T13:17:42.943

7@CarpetPython Apparently MATL can... – Denker – 2016-01-30T16:43:36.727

1@CarpetPython And Pyth – isaacg – 2016-01-31T05:12:35.053

9

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.

Martin Ender

Posted 2016-01-30T12:50:41.727

Reputation: 184 808

6EuclideanDistance 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 – 2016-01-31T01:18:46.783

1I'm working on a golfy Mathematica-based language >:) – Greg Martin – 2017-02-03T17:51:38.610

6

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.

Martin Ender

Posted 2016-01-30T12:50:41.727

Reputation: 184 808

That trick with :mh is very nice indeed – Luis Mendo – 2016-01-30T16:57:16.823

6

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

YoYoYonnY

Posted 2016-01-30T12:50:41.727

Reputation: 1 173

13uncurry ಠ_ಠ When cooking I sometimes wish to have an unsalt function. – flawr – 2016-01-30T14:27:47.877

@flawr https://en.wikipedia.org/wiki/Salt_(cryptography)?

– YoYoYonnY – 2016-01-30T14:38:15.063

2map + uncurry + zip rarely pays off, use zipWith: d a=sqrt.sum.zipWith(((^2).).(-))a. – nimi – 2016-01-30T21:16:57.910

1can't you save another couple of bytes by eta reduction? – jk. – 2016-02-01T15:05:17.483

@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 – 2016-02-02T14:29:42.760

6

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

alephalpha

Posted 2016-01-30T12:50:41.727

Reputation: 23 988

5

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!

Alex A.

Posted 2016-01-30T12:50:41.727

Reputation: 23 761

.5*⍨(+/-×-) saves a few bytes. – Dennis – 2016-01-30T19:14:38.997

3Can 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 – 2016-01-30T22:34:44.147

@steveverrill I <s>comment</s> put zombie fingers in just about all of my APL submissions here. ¯\(ツ) – Alex A. – 2016-01-31T03:39:52.363

@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 http://codegolf.stackexchange.com/a/70595/15599 Anyway, I like that you still have a single character smiley in your code.

– Level River St – 2016-01-31T08:39:39.623

4

Java, 130 117 114 107 105 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), @KevinCruijssen (9 bytes) and @DarrelHoffman (3 bytes)!

Golfed:

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

Ungolfed:

double d(float[] a, float[] b) {
  float x=0,s;

  for(int i=0; i<a.length; x+=s*s)
    s = a[i] - b[i++];

  return Math.sqrt(x);
}

ბიმო

Posted 2016-01-30T12:50:41.727

Reputation: 15 345

2You 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 – 2016-01-31T00:28:32.680

You can use int instead of double to save characters too, and declare i next to x. – rodolphito – 2016-01-31T00:49:41.637

1This 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. – Addison Crump – 2016-01-31T14:04:15.627

I totally forgot to shorten the function name.. @flawr thanks a lot for those tips, I didn't know you could do that. – ბიმო – 2016-01-31T17:12:44.827

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 – 2016-01-31T18:58:52.693

@DarrelHoffman thanks for saving me 3 bytes! I don't get it to work when I don't initialize x to zero. This might be relevant, I'm using javac version 1.8.0_66.

– ბიმო – 2016-01-31T20:14:09.873

@Bruce_Forte: Ah, my bad. I forgot that Java class member variables are initialized to 0, but local variables are not. Oh well. (My last few jobs have all been C++ or C#, been a while since I put on the Java-hat.) – Darrel Hoffman – 2016-01-31T20:28:20.370

However, if this were a full program, complete with class declaration and main function et al, you could use that trick. Of course then it wouldn't be close to competing with even BF, but that's Java for you... – Darrel Hoffman – 2016-01-31T20:35:42.420

1You can remove the public in front of the method to save 7 bytes, and you can also place the x+=s*s outside the for-loop so you don't need the comma (i.e. for(int i=-1;++i<a.length;s=a[i]-b[i])x+=s*s;) for -1 byte. – Kevin Cruijssen – 2017-01-17T10:31:04.147

@KevinCruijssen: Cheers for the 7 bytes! But about the s, I can't get this to work. This is the same as with Darrel's suggestion, the variable s wouldn't get initialized that way. – ბიმო – 2017-01-18T15:32:13.067

1@Bruce_Forte Ah, I see.. In that case you could use this: for(int i=0;i<a.length;x+=s*s)s=a[i]-b[i++]; (and I also changed the -1 to 0 for an additional byte) – Kevin Cruijssen – 2017-01-18T16:08:22.690

1@KevinCruijssen True. I like the change to 0 by using the operator precedence rules! Thanks for saving me a whole lot of bytes. – ბიმო – 2017-01-18T21:26:07.357

4

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.

Gareth

Posted 2016-01-30T12:50:41.727

Reputation: 11 678

Since the inputs are always the same length, you can drop the > and specify that input should be given as x y z,:a b c. – Bolce Bussiere – 2018-04-11T20:22:47.723

3

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.

Alex A.

Posted 2016-01-30T12:50:41.727

Reputation: 23 761

You can save 3 bytes by using an operator as the function name : Try it online!

– sundar - Reinstate Monica – 2018-07-02T23:29:39.537

3

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

Kyle Kanos

Posted 2016-01-30T12:50:41.727

Reputation: 4 270

3

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

Mego

Posted 2016-01-30T12:50:41.727

Reputation: 32 998

2

Python 2, 47 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

Logic Knight

Posted 2016-01-30T12:50:41.727

Reputation: 6 622

Works in Python3.6, but might not be optimal. – SIGSTACKFAULT – 2018-07-09T16:07:13.380

2

JavaScript ES7, 45 ES6, 37 bytes

a=>Math.hypot(...a.map(([b,c])=>b-c))

Expects an array of pairs of coordinates, one from each vector, e.g. [[1, 5], [2, 6], [3, 7], [4, 8]]. If that is unacceptable, then for 42 bytes:

(a,b)=>Math.hypot(...a.map((e,i)=>e-b[i]))

Expects two arrays of equal length corresponding to the two N-dimensional vectors, e.g. [1, 2, 3, 4], [5, 6, 7, 8]. Edit: Saved 3 bytes thanks to @l4m2. (Also, did nobody notice my typo?)

Neil

Posted 2016-01-30T12:50:41.727

Reputation: 95 035

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. – Denker – 2016-01-30T16:41:25.940

@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 – 2016-01-30T17:07:32.543

a=>b=>Math.hypot(...a.map((t,i)=>t-b[i])) – l4m2 – 2017-12-27T09:04:31.103

2

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

Level River St

Posted 2016-01-30T12:50:41.727

Reputation: 22 049

2

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

Addison Crump

Posted 2016-01-30T12:50:41.727

Reputation: 10 763

2

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

Hotkeys

Posted 2016-01-30T12:50:41.727

Reputation: 1 015

{sqrt [+] ([Z-] $_)»²} – Brad Gilbert b2gills – 2016-02-05T06:28:01.517

1

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.

rturnbull

Posted 2016-01-30T12:50:41.727

Reputation: 3 689

function(x,y)norm(x-y,"F") is shorter than your second version. – Giuseppe – 2018-04-11T15:56:10.003

1

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))))

pizzapants184

Posted 2016-01-30T12:50:41.727

Reputation: 3 174

1

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

corvus_192

Posted 2016-01-30T12:50:41.727

Reputation: 1 889

1

, 6 chars / 13 bytes

МŰМŷ…ï

Try it here (Firefox only).

Calculates norm of difference of input arrays.

Mama Fun Roll

Posted 2016-01-30T12:50:41.727

Reputation: 7 234

1

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.

Olivia Trewin

Posted 2016-01-30T12:50:41.727

Reputation: 351

1

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

Mego

Posted 2016-01-30T12:50:41.727

Reputation: 32 998

1

Haskell, 32 bytes

((sqrt.sum.map(^2)).).zipWith(-)

λ> let d = ((sqrt.sum.map(^2)).).zipWith(-)
λ> d [1] [3]
2.0
λ> d [1,1] [1,1]
0.0
λ> d [1,2] [3,4]
2.8284271247461903
λ> d [1..4] [5..8]
8.0
λ> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
λ> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522

Rodrigo de Azevedo

Posted 2016-01-30T12:50:41.727

Reputation: 177

232 bytes – Angs – 2018-07-02T11:15:03.120

@Angs Thanks for the improvement. After some tinkering, I found a way to remove 6 more bytes (by removing map and parentheses). – Rodrigo de Azevedo – 2018-07-09T15:50:55.303

I'm sorry to intervene again, but sqrt$sum$(^2)<$>zipWith(-) is not a valid anonymous function. The underlying rule is actually quite simple: If you can write f = <mycode> and f afterwards performs the required task, then <mycode> is a valid anonymous function. In your case you need to add f p q = <mycode> p q, so <mycode> on it's own is not valid. – Laikoni – 2018-07-10T09:52:58.200

1@Laikoni You're right. I edited my answer and used Angs's suggestion. If you find a way to shorten it, please let me know. – Rodrigo de Azevedo – 2018-07-15T11:20:22.010

0

Clojure, 48 bytes

#(Math/sqrt(apply +(for[d(map - % %2)](* d d))))

NikoNyrh

Posted 2016-01-30T12:50:41.727

Reputation: 2 361

0

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)

Magic Octopus Urn

Posted 2016-01-30T12:50:41.727

Reputation: 19 422

0

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.

Abel Tom

Posted 2016-01-30T12:50:41.727

Reputation: 1 150

0

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

Walerian Sobczak

Posted 2016-01-30T12:50:41.727

Reputation: 101

Welcome to PPCG! Nice first post! – Rɪᴋᴇʀ – 2017-11-24T02:15:07.363

0

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))]

Taylor Scott

Posted 2016-01-30T12:50:41.727

Reputation: 6 709

0

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

xbarbie

Posted 2016-01-30T12:50:41.727

Reputation: 91

0

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

recursive

Posted 2016-01-30T12:50:41.727

Reputation: 8 616

0

C (gcc), 79 bytes

TIO requires compiler flag -lm. GCC of MinGW (that I use) does not.

f(p,q,d,s)float*p,*q,s;{for(s=0;d--;)s+=pow(p[d]-q[d],2);printf("%f",sqrt(s));}

Try it online!

gastropner

Posted 2016-01-30T12:50:41.727

Reputation: 3 264

0

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

Tim

Posted 2016-01-30T12:50:41.727

Reputation: 2 789

2Drop a few more: sum([(x-y)**2 for x,y in zip(a,b)])**.5 – Benjamin – 2016-01-31T04:55:58.730

0

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.

Stuart Bruff

Posted 2016-01-30T12:50:41.727

Reputation: 501

0

Pyke, 7 bytes

,A-MXs,

Try it here!

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

Blue

Posted 2016-01-30T12:50:41.727

Reputation: 26 661

0

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

Value Ink

Posted 2016-01-30T12:50:41.727

Reputation: 10 608