[Question]
  [
Euclidean distance between two lattice points \$(x\_1, y\_1)\$ and \$(x\_2, y\_2)\$ on a plane is: \$\sqrt{(x\_1 - x\_2)^2 + (y\_1 - y\_2)^2}\$.
Imagine now a lattice `N x N` replicated infinitely many times next to itself. The two points \$(x\_1, y\_1)\$ and \$(x\_2, y\_2)\$ also get replicated. Euclidean distance on a torus is then the minimal distance between all these points.
Input: `x1, y1, x2, y2` and `N`. Arrange these in any convenient order or way (e.g. represent \$(3,4)\$, \$(5,6)\$ as 4 arguments `3, 4, 5, 6`, two complex numbers \$3+4j\$, \$5+6j\$, a list `[[3,4],[5,6]]`, a list `[3,4,5,6]` or anything that's not too bizarre). Coordinates must be integers in the range `0..N-1` or `1..N`. The size of the torus (`N`) must be an integer (you can assume `1 < N < 100`).
Output: a real number, with precision better than \$1\%\$.
Test cases:
| x1 | y1 | x2 | y2 | N | Result |
| --- | --- | --- | --- | --- | --- |
| 1 | 0 | 1 | 1 | 2 | 1.00 |
| 2 | 3 | 2 | 3 | 4 | 0.00 |
| 0 | 0 | 2 | 2 | 4 | 2.83 |
| 0 | 9 | 1 | 1 | 10 | 2.24 |
| 9 | 0 | 9 | 8 | 10 | 2.00 |
| 12 | 34 | 56 | 78 | 99 | 62.23 |
| 0 | 0 | 98 | 98 | 99 | 1.41 |
 
  
[Answer]
# [R](https://www.r-project.org), 40 bytes
```
\(a,b,N)sum(pmin((d=a-b)%%N,-d%%N)^2)^.5
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bdBLCsIwEIBh3HqKghQSmJYkfZgscoWcQCqpQShYK32cxk1duPU-ehrbhkqL2SSz-Pgz5P6o-1db1VVh9OVoiqaVz649B_yNDkhDDgo3XYluZXFFyEgd5Nj3FQRmOHHGcBYm1n82ySqDtDwhCgRDPg0Ug5IMezuPbv8hg8jCaVAyHiFxQDIXGbAfZCGPnFasXqfEYhY7sJjDAvgCOyQddoytTVLYT1qIUadD273I3OYgFp6GMbW_1_f2_gI)
Input the two points as vectors `a` and `b`.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~18~~ 16 bytes
-2 bytes thanks to @ngn.
Function taking input as `f[N;(x1,y1;x2,y2)]`.
```
{%+/&/x*x!:y-|y}
```
[Try it online!](https://ngn.codeberg.page/k#eJxFjcEOgjAQRM/0K9ZGBTSWtiDS9h84eAUSLsLFeBGTNui/u60Qk+1k83ZmOuh5d8z2mT3YjXant/sQMuq5scI4Yaw0TpraXG/P133qCAxNbSBJwjU1SbinaYehSVMBEYdIhJGojHMCALjmAaAWaFkwD24ZBrFkVb5gtZYIb2Cy8FwFO2q18l+N8MWYP5cQXfCm0FJiKP//oarl+WJWCEp6rrcji1kc03aiLeoDly82wDIm)
`y-|y` Subtract the reversed list of points from the list of points. This results in component-wise distances in both directions.  
`x!:` Take all values mod *N*. Updates x.  
`x*` Square each value.  
`&/` take the element-wise minimum between positive and negative difference.  
`%+/` Sum, then take the square root.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~¬†8¬†~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
·∫°/¬´·∫°¬•√Ü·∏ä
```
A dyadic Link that accepts the coordinates as a pair of pairs\* of integers\*\* on the left and the size as an integer\*\* on the right and yields the Euclidean toroidal distance.
\* I guess this will work in any integer number of dimensions too.
\*\* Will work with floats too (up to floating point inaccuracies, of course).
**[Try it online!](https://tio.run/##y0rNyan8///hroX6h1YDyUNLD7c93NH1////aAMdy1idaEMdw9j/hgYA "Jelly ‚Äì Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hroX6h1YDyUNLD7c93NH1//By/UdNa/7/jwYCBUMdBQWDWB0FCMswFshUMIrV4VIASRoBOcZgSQgLJGkCkzSA6zQC68GQtEQ11tAAJmkJ1wliWaBIGgINMzYBSZqa6SiYgyUtLTHstLQACiMkYwE "Jelly ‚Äì Try It Online").
### How?
\$\text{Distance} = \sqrt{\left (|x\_1-x\_2| \land ||x\_1-x\_2|-N| \right )^2 + \left (|y\_1-y\_2| \land ||y\_1-y\_2|-N| \right )^2}\$
```
·∫°/¬´·∫°¬•√Ü·∏ä - Link: Coordinates=[[x1, y1], [x2, y2]]; Size=N
 /      - reduce (Coordinates) by:
·∫°       -   ([x1, y1]) absolute difference ([x2, y2])
              -> D = [|x1-x2|, |y1-y2|]
    ¬•   - last two links as a dyad - f(D, N):
   ·∫°    -   (D) absolute difference (N) (vectorises)
              -> D2 = [||x1-x2|-N|, ||y1-y2|-N|]
  ¬´     -   (D) minimum (D2) (vectorises)
              -> M = [min(|x1-x2|, ||x1-x2|-N|), min(|y1-y2|, ||y1-y2|-N|)]
     √Ü·∏ä - norm = vector_length = square_root(sum(squared_values)))
            -> (min(|x1-x2|, ||x1-x2|-N|)^2 + min(|y1-y2|, ||y1-y2|-N|)^2)^(1/2)
```
[Answer]
# [julia](https://julialang.org/), 43 bytes
Notice that for any point \$x\$, the \$N\$-toroidal distance from \$x\$ to \$(N/2, N/2)\$ is the Euclidean distance from \$\mathrm{mod}(x, N)\$ to \$(N/2, N/2)\$.
Hence, we can find the \$N\$-toroidal distance between \$a\$ and \$b\$ by computing the Euclidean distance from \$\mathrm{mod}(a-b+(N/2, N/2), N)\$ to \$(N/2, N/2)\$.
```
d(a,b,N)=sum(@. (mod1(a-b+N/2,N)-N/2)^2)^.5
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XdDRCoIwFAZggq56ikE3E-famdO2i6An8AWiwJDAUIvSp-nGGx-qnqYzXTGEwQ_j23_GeQ3Xrirzvh-69hLpd1jQnJ1ZFuyeXU33nND6VgDNo3OYbSTeRxjBCQ9PpiefxfL-KJu2amhBD8CIODJiEzBlEJA1gZUnJCOxFS7VKIQvhOtAIf9Cch3PkPEGgXBKKl8ZV4WpPeUTsB9RFiUpI1vLjBlZim3zmVObRuNB4AqmZfz2-AU)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~38~~ 33 bytes
```
nÔí°Norm[Min[#,n-#]&/@Abs[#-#2]]&
```
Thanks to @att!  
Where `Ôí°` stands for `\[Function]`
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@/9pIV@@UW50b6ZedHKOnm6yrFq@g6OScXRyrrKRrGxav8DijLzShzSog0NYqOrDXQsa3UUqg11DGtjuWAylpZgGQOQjKWFjqVFbex/AA "Wolfram Language (Mathematica) ‚Äì Try It Online")
Input: `[N][{x1,y1}, {x2,y2}]`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Œ±D≈†-√∏‚Ç¨√ünOt
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3EaXowt0D@941LTm8Pw8/5L//6MNjXSMTWK5ok3NdMwtYrksLQE "05AB1E ‚Äì Try It Online")
-1 thanks to *@KevinCruijssen*
#### Explanation
```
Œ±D≈†-√∏‚Ç¨√ünOt  # Implicit input
Œ±           # Absolute difference between the first two inputs
 D          # Duplicate this pair
  ≈†         # Triple swap so the input is second
   -        # Subtract the absolute difference between the
            # first two inputs from the third input
    √∏       # Zip this with the absolute difference
     ‚Ç¨√ü     # Minimum of each inner pair
       n    # Square each
        O   # Sum the list
         t  # Square root the sum
            # Implicit output
```
[Answer]
# JavaScript (ES7), 64 bytes
Expects `(x1,y1,x2,y2,N)`.
```
(x,y,X,Y,n)=>((g=d=>(d*=d)<(q=n-d**.5)*q?d:q*q)(X-x)+g(Y-y))**.5
```
[Try it online!](https://tio.run/##ddBBDoIwEAXQvafoslNbaAsqNVavAUtCgWgMiBgDp8cSajSIi5@/mJfppJf0mbbZ/Xx7sKo2@VDoAXe0pzFNaAX6iHGpjS1DtIEDbnTFDCHeBkhzMvuGNIBj1sG6xAnrAcbRkNVVW19z71qXuMBIUIS4jXCRAMj3kfA4X82otONgJK7DifIFyt1W6eKo9KJgiarPAYK/qQznVLmtY0ff9OcAYR8NQoo2W4p2lio10a1dG/w5VkUu6v0FoRhe "JavaScript (Node.js) ‚Äì Try It Online")
### Commented
```
( x, y,       // (x, y) = coordinates of the 1st point
  X, Y,       // (X, Y) = coordinates of the 2nd point
  n           // n = size of the torus
) => (        //
  ( g = d =>  // g is a helper function taking d
    (d *= d)  // square d
    <         // and compare it with
    ( q =     // q defined as:
      n -     //   the difference between n and
      d ** .5 //   the square root of d (which is the
              //   absolute value of the original d)
    ) * q     // multiplied by itself
    ?         // if d is less than q¬≤:
      d       //   return d
    :         // else:
      q * q   //   return q¬≤
  )(X - x) +  // 1st call to g with d = X - x
  g(Y - y)    // 2nd call to g with d = Y - y
) ** .5       // square root of the sum
```
[Answer]
# [Factor](https://factorcode.org/), 52 bytes
```
[ v- 2dup n-v rot '[ [ _ rem ] map ] bi@ vmin norm ]
```
[Try it online!](https://tio.run/##bdA9b8IwEAbgPb/i3TqBkkABtwsb6tKl6hQhlKYXNSqxzdmJFKH89vRigooE/jrpHp9PcpkX3vDw@fH2vntBnfufeUtjyuGXWNMRJXchD0enhnRBDrlzpnCwTN53livt8RpF5wgyzkhlJ4jRh5hI7CdZBl0EucRbiaeaVOa/JHEg9eC5QGqqUtjckFKjS49lwOcV1nd87ac24xqxHzK0M6TfjYWetWDj8ZQhwwFMNfbyD1bOr2qLtq40tGHJSlFZsfMLIfkSaxyFi/PhDw "Factor ‚Äì Try It Online")
Takes input as `N { x1 y1 } { x2 y2 }`.
```
                   ! 10 { 9 0 } { 9 8 }
v-                 ! 10 { 0 -8 }
2dup               ! 10 { 0 -8 } 10 { 0 -8 }
n-v                ! 10 { 0 -8 } { 10 18 }
rot                ! { 0 -8 } { 10 18 } 10
'[ [ _ rem ] map ] ! { 0 -8 } { 10 18 } [ [ 10 rem ] map ]
bi@                ! { 0 2 } { 0 8 }   (apply quot to both points)
vmin               ! { 0 2 }
norm               ! 2.0
```
[Answer]
# [Python](https://www.python.org), ~~63~~ ~~59~~ 57 bytes
*Edit: -4 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) and -2 thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor).*
```
lambda x,y,X,Y,N:abs((x-X+(k:=N/2))%N-k+((y-Y+k)%N-k)*1j)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3LXMSc5NSEhUqdCp1InQidfysEpOKNTQqdCO0NbKtbP30jTQ1Vf10s7U1NCp1I7WzwRxNLcMsTagBUwuKMvNKNNI0DHUMdAyBEKiBCyZmpGOsA8ImSGIGQHVGQIgqZgnWa2iAJGipAxK2QBU0BBpnomNqpmNuoWNpiWaspQUYAYUhjluwAEIDAA)
Port of [Damian Pavlyshyn's comment](https://codegolf.stackexchange.com/questions/260743/calculate-euclidean-distance-on-a-torus#comment573669_260757).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~60~~ 56 bytes
```
->a,b,n{(-4..4).map{|c|(a-b-n*(c%3-1+1i*c/=3)).abs}.min}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ0knr1pD10RPz0RTLzexoLomuUYjUTdJN09LI1nVWNdQ2zBTK1nf1lhTUy8xqbhWLzczr/Z/gUJatKEOSE7HKJYLxDPSNgayQYQJRMAAyDOC8ywzIaoNDaB8HUttCwTXEKjTJFPH1EzbHChqaQkzwtJC2xIi8B8A "Ruby ‚Äì Try It Online")
## How?
Input as complex numbers.
`(a-b).abs` is the distance between a and b on the complex plane. We have to move b into the 8 adjacent spaces, and calculate distance between the original a and the new b, then take the minimum.
Iterating from -4 to +4 we get the offset table using `c%3-1` for the real part, and `c/3` for the imaginary part:
```
+-----+-----+-----+
| -4  | -3  | -2  |
|-1-i | -i  | 1-i |
+-----+-----+-----+
| -1  |  0  |  1  |
| -1  |  0  |  1  |
+-----+-----+-----+
|  2  |  3  |  4  |
|-1+i |  i  | 1+i |
+-----+-----+-----+
```
[Answer]
# Python3, 79 bytes:
```
lambda x,y,X,Y,n:(min(abs(x-X),n-abs(x-X))**2+min(abs(y-Y),n-abs(y-Y))**2)**0.5
```
[Try it online!](https://tio.run/##XYzBCoMwEETv/YoeEzspSdQ2KfQ/FHqJFKlQ02A9mK9PEyGgZXdgeLM7zs@vjy2Vm0J/f4S3GbunOS7waNDC3sg4WGK6L1lYQ2FZtrQo5ClnnrU5SzZlUfxcBzcNdiY9EeAQcSSlh8wkSiRVG8bjnYyzZ3r9FXwDNRJWeyhiXYX6gquC1n@1Wq0bcfgB)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 9 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
-AD‚Å∂_·ªå¬≤S∆≠
```
#### Explanation
```
-AD‚Å∂_·ªå¬≤S∆≠  # Implicit input
-A         # Absolute difference between first two inputs
  D        # Duplicate the pair
   ‚Å∂_      # Subtract from the third input
     ·ªå     # Elementwise dyadic minimum
      ¬≤    # Square each
       S   # Sum the list
        ∆≠  # Square root the sum
           # Implicit output
```
#### Screenshot
[![Screenshot](https://i.stack.imgur.com/qy84Am.png)](https://i.stack.imgur.com/qy84A.png)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `·∏ã`, ~~10~~ 9 bytes
```
Œµ:?$-√û‚àµ‚àÜ/
```
Thanks @TheThonnu!
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyLhuIsiLCIiLCLOtTo/JC3DnuKIteKIhi8iLCIiLCJbMTIsMzRdXG5bNTYsNzhdXG45OSJd)
Input: `[x1, y1] \n [x2, y2] \n N`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Ôº©‚ÇÇŒ£Ôº•Œ∏‚åäÔº∏‚Åª‚Üî‚ÅªŒπ¬ßŒ∑Œ∫‚ü¶‚Å∞Œ∂‚üß¬≤
```
[Try it online!](https://tio.run/##LcnLCsIwEIXhV5nlBEbQei2uiisXhaLLkEWsgYamic1FxZePAT2r7@f0g/S9kybnzmsb8SRDxOucpFcX5wrThK184EzQaqunkp17KY@lUsDmFpxJUf1TEzTxbO/qjQPByBgj4EuCjyio2G/HnDlfVQTrjSj3dkewPxTVtciLp/kC "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Takes input as two pairs of coordinates and a number. Explanation:
```
    Œ∏               First input
   Ôº•                Map over coordinates
          Œπ         Corrent coordinate
         ‚Åª          Subtract
            Œ∑       Second input
           ¬ß        Indexed by
             Œ∫      Current index
        ‚Üî           Absolute value
       ‚Åª            Vectorised subtract
              ‚ü¶  ‚üß  List of
               ‚Å∞    Literal integer `0` and
                Œ∂   Third input
      Ôº∏             Vectorised raise to power
                  ¬≤ Literal integer `2`
     ‚åä              Take the minimum
  Œ£                 Take the sum
 ‚ÇÇ                  Take the square root
Ôº©                   Cast to string
                    Implicitly print
```
[Answer]
# SAS 4GL, 71 bytes (or 57)
1. *The answer (in short, just "the point"):*
```
data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run;
```
---
2. *The answer and all details [with details ;-)]:*
Input:
```
data input;
/* x1 y1 x2 y2 N Result */
input x y p q n r;
cards;
1   0   1   1   2   1.00
2   3   2   3   4   0.00
0   0   2   2   4   2.83
0   9   1   1   10  2.24
9   0   9   8   10  2.00
12  34  56  78  99  62.23
0   0   98  98  99  1.41
;
run;
/* to print input data */
proc print data=input;
run;
```
Immediately after "input code" run:
Code:
```
data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run;
```
The:
```
data;set;...run;
```
part is mandatory for every SAS 4GL code so if we select only the "calculation" part:
```
a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);
```
it is 57 bytes ;-)
Code formatted:
```
data;
  set;
  a = abs(x - p);
  b = abs(y - q);
  d = sqrt(                   
            (a >< (N - a))**2 
          + (b >< (N - b))**2 
          );
run;
```
Comments:
* `i><j` is minimum of i and j, `i**j` is i to power j
* `sqrt(expression)` is the same number of bytes as `(expression)**.5`,
* brackets arounf `N-b` are necessary because `><` takes precedence over substraction,
* result dataset is named `DataX` where X is the first integer not yet used for naming default dataset.
Log:
```
1    data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run;
NOTE: There were 7 observations read from the data set WORK.INPUT.
NOTE: The data set WORK.DATA4 has 7 observations and 9 variables.
NOTE: DATA statement used (Total process time):
      real time           0.00 seconds
      cpu time            0.00 seconds
```
---
[Answer]
# [Scala](http://www.scala-lang.org/), ~~137~~ 96 bytes
Saved 41 bytes thanks to the comment of @corvus\_192
---
[Try it online!](https://tio.run/##dY5RS8MwEMff8ynuMcGrtHXqUqgg@OKDTyJsiEg62y2jTWsadWX0s9drtCDbDHfHcb//3T/tSpVqqLNtvnLwoLSBPftUJRQJvzcOD1KkN3f1R1bm6X7QVVNbB5Vym/NXxnfY4QKXaEjTvlvHm/qLV9pwlbV8FywEmmBqBcbi7C/vguXEx3bkYugZwFtekMOosus2gVtrVff86Kw26xeRwJPRDlL6MtBraOpKwwseIYQIkQ@6dEBjhAua@zo7oqHfjX2cpHK6HIVHWPplqvOTOBpNZwiXVwjXJJHyH3s5/80fQc96NnwD)
```
import math._
(x,y,X,Y,n)=>sqrt(pow(min(abs(x-X),n-abs(x-X)),2)+pow(min(abs(y-Y),n-abs(y-Y)),2))
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
√≠aV √ãmDaW√Éx¬≤¬¨
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7WFWIMttRGFXw3iyrA&input=WzEyIDM0XQpbNTYgNzhdCjk5)
```
√≠aV √ãmDaW√Éx¬≤¬¨     :Implicit input of arrays U=[x1,y1] & V=[x2,y2] and integer W=N
√≠ V               :Interleave U & V
 a                :  Reducing each pair by absolute difference
    √ã             :Map each D
     m            :  Minimum with
      DaW         :    Absolute difference of D & W
         √É        :End map
          x       :Reduce by addition after
           ¬≤      :  Squaring each
            ¬¨     :Square root
```
[Answer]
# [Arturo](https://arturo-lang.io), 57 bytes
```
$=>[x:abs&-&y:abs&-&n:&sqrt+^min@[x,n-x]2(min@[y,n-y])^2]
```
[Try it](http://arturo-lang.io/playground?N0wy1v)
Takes input as `x1 x2 y1 y2 N`.
```
$=>[                 ; a function
    x:abs&-&         ; assign absolute value of first arg minus second arg to x
    y:abs&-&         ; assign absolute value of third arg minus fourth arg to y
    n:&              ; assign fifth arg to n
    (min@[y,n-y])^2  ; minimum of y and n-y squared
    ^min@[x,n-x]2    ; minimum of x and n-x squared
    +                ; add
    sqrt             ; square root
]                    ; end function
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 17 bytes
```
{‚àö+¬¥√óÀú‚åä¬¥ùï®|-‚ä∏‚ãà-¬¥ùï©}
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=VG9yb2lkYWxfZGlzdCDihpAge+KImivCtMOXy5zijIrCtPCdlah8LeKKuOKLiC3CtPCdlal9CgoxMCBUb3JvaWRhbF9kaXN0IOKfqOKfqDAsOeKfqSzin6gxLDHin6nin6k=)
```
{‚àö+¬¥√óÀú‚åä¬¥ùï®|-‚ä∏‚ãà-¬¥ùï©}  # function taking N as left arg (ùï®)
                    # and [[x1,y1],[x2,y2]] as right arg (ùï©):
              -¬¥ùï©   # vectorized fold-subtract: [x1-x2,y1-y2]
          -‚ä∏‚ãà      # joined to negative of itself: [[x1-x2,y1-y2],[x2-x1],[y2-y1]]
        ùï®|          # all modulo N
      ‚åä¬¥            # vectorized fold-minimum
    √óÀú              # vectorized multiply each element by itself
  +¬¥                # sum (fold-addition)
 ‚àö                  # square-root
```
[Answer]
# [Scala](https://www.scala-lang.org/), 104 bytes
Golfed version. [Try it online!](https://tio.run/##lZJNT4QwEIbv@yvmYtLGLsuXK2DYxMSLB7kYT5uNKR@uGD5LV6OE345TJIT1gvbQ9J32fabtTBPxjPdl@JZEEh54WkC7WgHEyQvkqAgXx8aDWyH45/5RirQ4HqgHT0UqwcejgKPCqMwKIktRpjHPnuO0kWSwEIOBThlMwkBhUqpsmw0Yi36TgTX5R2FPfn3Rr8/zmyr33G9qjvUXhPv7CYY@MAaEaS8i3PktUDjniOVfVC@3J8LVlsG1YrguMpCwxVtY//sL10H7nGFotipHh9VXxT8DePCD2N8X8jASxjXO1N/dlacwS7AjesJZyAIMte88g9jn2ldakZBqOa/aiDcJqViN26Ra15cBvQi6m5zLV62phSSxOkWEvxtCVflBhkWOfShYsBaUYe9ozSmnXd/13w)
```
(a,b,N)=>{val d=a.zip(b).map{case(p,q)=>(p-q+N)%N};math.sqrt(d.map(r=>math.pow(math.min(r,N-r),2)).sum)}
```
Ungolfed version. [Try it online!](https://tio.run/##lZLNToQwFIX38xRnY9JGZIDBEUjGxMSNC9kYV2ZiyhTHGv6EjkYn8@x4iw4BN2hX9zQ9X@9tT7MRmWjbMnlJNxq3QhXYz2aATJ@Qk2Ki3jYRrupafDzc6VoV2zWPcF8ojRUdBa2KdnVWMF3WpZIie5Sq0ayzMNeCwy30wiXhcW5s8zncSb9nYdH7f4Tf@51JvzO83zN3D/2eHSz@ggh/j@A6HaNDeP4kIhx2QSIYI6Zf0Uzu94TzpYULwwhDYhBhSV0s/vcWYUD2IcO1ffMdh@PvjwnimIGbQq8tJGMZR6CCcnFd7pIs7ZPxJjJIUsL@VBVLuJ2LCntsRJOCCUUcxbG6NDXOSOAUMccJYmrD@HOhn@3mtdZMGiuTypzudqvynXVFTiGVhIqJINV3vOxml/NumMOsbb8A)
```
object Main {
  def main(args: Array[String]): Unit = {
    println(toroidal_dist(Array(1, 0), Array(1, 1), 2))    // 1
    println(toroidal_dist(Array(2, 3), Array(2, 3), 4))    // 0
    println(toroidal_dist(Array(0, 0), Array(2, 2), 4))    // 2.83
    println(toroidal_dist(Array(0, 9), Array(1, 1), 10))   // 2.24
    println(toroidal_dist(Array(9, 0), Array(9, 8), 10))   // 2
    println(toroidal_dist(Array(12, 34), Array(56, 78), 99)) // 62.23
    println(toroidal_dist(Array(0, 0), Array(98, 98), 99)) // 1.41
  }
  def toroidal_dist(a: Array[Int], b: Array[Int], N: Int): Double = {
    val d = a.zip(b).map { case (ai, bi) => (ai - bi + N) % N }
    math.sqrt(d.map(di => math.pow(math.min(di, N - di), 2)).sum)
  }
}
```
]