Note: The title of this question should be "Loop It", but because title needs to be at least 15 characters, there are some invisible spaces. This note is such that the challenge can be searched for.


Given a finite list of unique integral points in the plane, find a polygon whose vertices are exactly those points, which does not self intersect.


  • As input you can take e.g. two lists with each the x- and y-coordinates or a list of pairs.
  • The input list contains at least 3 points.
  • Note that this means there is never a unique solution.
  • The list of inputs is can be assumed to be not co-linear (the points cannot be contained in one line), this means there actually is such a non-self-intersecting polygon.
  • The angles at each vertex is arbitrary, this includes 180°.
  • For an input of length n, the output should be a permutation (p1,p2,p3,...,pn) of (1,2,3,...,n) where the k-th entry pk represents the p-th point in the input list. This means we have a line from p1 to p2, a line from p2 to p3 etc, as well as a line from pn to p1. (You can also use the 0-based indices.) Alternatively you can just output the list of input points in the right order.


Let's say we have the points [(0,0),(0,1),(1,0),(-1,0),(0,-1)] and we want to represent following path:

enter image description here

This means we would output the list [5,1,4,2,3]

Here some more suggestion to try (I recommend looking at the corresponding plots to verify the goals.)




Menger Sponge
  • \$\begingroup\$ If we have 4 points O(0,0), A(1,0), B(0,1), C(0,2), is the polygon OABC self-intersecting? \$\endgroup\$
    – ngn
    Jan 13, 2018 at 15:25
  • \$\begingroup\$ @ngn That is a good point I did not consider! I'll have to think about it. If you have any argument for or against this please let me know. \$\endgroup\$
    – flawr
    Jan 13, 2018 at 15:50
  • \$\begingroup\$ @ngn I'd count this polygon as self-intersecting. The reason is that I'd define a polygon to be self intersecting if there is a common point of two edges that is not an endpoint. \$\endgroup\$
    – flawr
    Jan 13, 2018 at 15:53
  • \$\begingroup\$ @flawr I must withdraw my answer then, it fails when there are multiple co-linear points at maximum angle from the reference point. \$\endgroup\$
    – ngn
    Jan 13, 2018 at 16:15

3 Answers 3


Mathematica 29 28 Bytes

FindShortestTour (16 Bytes) does the trick but delivers some extraneous info not asked for (the path length, and a return to the starting point).


gives just the answer ( -1 byte thanks to @user202729 )

To visualize, use Graphics@Line[g[[%]]], where % is the permutation found above and g is the original point list.

Here is the visualization of the solution for the Menger Sponge: enter image description here

Here is a solution on a 1000 random points:

enter image description here

The key here is knowing that the shortest tour or traveling salesman problem solution will never yield intersections when Euclidean distance is used as the metric. One of the steps to localize a solution and ensure optimality is to remove such intersections.

  • 6
    \$\begingroup\$ Use NP algorithm to solve P problem just because it's shorter. +1 (???). \$\endgroup\$
    Jan 13, 2018 at 3:50
  • 1
    \$\begingroup\$ @* seems to save a byte. \$\endgroup\$
    Jan 13, 2018 at 3:52
  • 2
    \$\begingroup\$ Quick explanation for people who need it \$\endgroup\$
    Jan 13, 2018 at 3:58

JavaScript (ES6), 365 341 bytes

Without any built-in, this turned out to be much longer than I expected. Many bytes are spent detecting collinear overlapping segments.

Takes input as an array of [x,y] coordinates. Returns a permutation of the input.



This snippet logs the output and draws the corresponding path in a canvas.


draw(f([[0,0],[0,1],[1,0]]), 1, 1)
draw(f([[0,0],[0,1],[1,0],[-1,0],[0,-1]]), 61, 21)
draw(f([[4,0],[1,0],[3,0],[0,0],[2,0],[0,1]]), 101, 1)

function draw(a, dx, dy) {

  ctx = C.getContext('2d');
  [...a, a[0]].forEach(p => ctx.lineTo(p[0] * 20 + dx, p[1] * 20 + dy));
<canvas id=C></canvas>


Here is the structure of the main recursive function f(), leaving aside the intersection testing code for now:

f = (a, p = []) =>                    // a = array of points, p = current path
  [...p,                              // build a closed path array P[] by adding the first
         p[0]]                        // point at the end of p[]
  .some((A, i, P) =>                  // for each point A at position i in P:
    P.some((C, j) =>                  //   for each point C at position j in P:
      j > i + 1 &&                    //     test whether C is at least 2 positions after A
      P[++j +                         //     and C is not the last point
              !i] &&                  //     and i > 0 or C is not the penultimate point
      intersection(                   //     and there's an intersection between
        A, P[i + 1], C, P[j]          //     the segments (A, P[i + 1]) and (C, P[j + 1])
      )                               //     (j was incremented above)
    )                                 //   end of inner some()
  ) ?                                 // end of outer some(); if truthy:
    0                                 //   discard this path by stopping recursion
  :                                   // else:
    a[0] ?                            //   if there's at least one remaining point:
      a.some((_, i) =>                //     for each remaining point at position i:
        r = f(                        //       do a recursive call with:
          b = [...a],                 //         a copy b[] of a[] without a[i] and
          p.concat(b.splice(i, 1)))   //         the extracted point added to the path
      ) && r                          //     end of some(); return the result, if any
    :                                 //   else:
      p                               //     this is a valid path: return it

Below is the detail of the intersection() test. This page provides a comprehensive explanation about the algorithm used.

[                                     // build an array containing:
  E = o(A, B = P[i + 1], C, S = []),  //   E = test of (A, B, C) (+ initialization of S[])
  F = o(A, B, D = P[j]),              //   F = test of (A, B, D)
  G = o(C, D, A),                     //   G = test of (C, D, A)
  H = o(C, D, B)                      //   H = test of (C, D, B)
]                                     //
.some(v =>                            // the segments are collinear and overlapping if:
  !v &                                //   any value above is 0
  !S.pop()                            //   and the corresponding entry in S[] is falsy
) |                                   // the segments intersect if:
E != F & G != H                       //   E is not equal to F and G is not equal to H

Finally, here is the definition of the helper function o():

o = (                                             // given three points represented by
  [p, P], [q, Q], [r, R]                          // a lowercase letter for x
) =>                                              // and an uppercase letter for y:
  Math.sign(                                      //
    (                                             //   1) prepend to the array S[]
      S = [                                       //      a boolean which is true if the
        (p > q ? r < q | r > p : r < p | r > q) | //      segment (P, Q) would not contain
        (P > Q ? R < Q | R > P : R < P | R > Q),  //      the point R, assuming that the
        ...S                                      //      3 points are collinear
      ],                                          //
                                                  //   2) return the orientation of P, Q, R:
      Q - P                                       //        -1 = counterclockwise
    ) * (r - q) - (q - p) * (R - Q)               //         0 = collinear
  )                                               //        +1 = clockwise
  • \$\begingroup\$ ... explanation please? \$\endgroup\$
    Jan 13, 2018 at 3:59
  • 1
    \$\begingroup\$ @user202729 (*wipes hand across forehead*) Done! \$\endgroup\$
    – Arnauld
    Jan 13, 2018 at 12:23

APL (Dyalog Classic), 42 38 bytes


Try it online!

Input is a list of coordinate pairs. Output is a 0-based permutation.

is the list of points - the argument to { }

⍵[⊃⍋↑⍵] is the leftmost-lowest point

⍵- translates all points so that leftmost-lowest is at the origin of the coordinate system

0j1 the imaginary unit i=sqrt(-1)

0j1⊥¨ decodes the coordinates as if digits in a base-i number system - i.e. turns (x,y) into a complex number ix+y

z← assign to z

12○ computes the complex numbers' arguments, a.k.a. theta angles, or APL circular function 12

(⍪,(|z)ׯ1*⊢=⌈/) is a train that computes a boolean mask of where the angles are at a maximum (⊢=⌈/), turns the 0 1 in the mask into 1 ¯1 by raising ¯1 to the corresponding power (¯1*), multiplies by the magnitudes of the complex numbers |z, and concatenates that to the right (,) of a tall thin 1-column matrix () of the angles.

grade - returns the permutation that would sort the rows of the matrix lexicographically in ascending order

  • \$\begingroup\$ @user202729 they will be sorted according to the second criterion - distance (i.e. circular function 10, aka complex magnitude) \$\endgroup\$
    – ngn
    Jan 13, 2018 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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