1

I have a list of connected line segments. How to get the polygons.

let lines = [
    [10, 10, 200, 10],
    [10, 10, 10, 200],
    [10, 200, 200, 10],
    [200, 10, 390, 10],
    [200, 10, 390, 200],
    [390, 10, 390, 200],
    [10, 200, 10, 390],
    [390, 200, 390, 390],
    [10, 390, 390, 390],
    [200, 10, 200, 200],
    [10, 200, 200, 200],
];

Sample code visualisation:

enter image description here

// poly 1 would be something like this.
poly1 = [
    [10, 10],
    [200, 10],
    [10, 200],
];
mazznoer
  • 103
  • 2
  • 9
  • You could build a Doubly Connected Edge List (DCEL) from your line arrangement and extract the faces. Here's a Javascript [implementation](https://github.com/yubowenok/LineArrangement), with a link to a cool demo. – RaffleBuffle Apr 13 '20 at 04:57

1 Answers1

2

I'd structure the solution like this:

  1. Go through each element in lines and match one line with the other, e.g. element 1 and 2 would match in [10,10]
  2. Go through each pair of lines retrieved from 1. and seek through lines for a third line that matches the pair of lines unmatched start/end points. E.g. element 1 and 2 would have unmatched start/end points in [200,10] and [10,200] respectively, this would match with element 3.

Codewise I think the best structure is:

  • One function matchCoordinates(coordinateA,coordinateB) that takes two coordinate pairs and returns boolean match.
  • One function matchLines(lineA,lineB) that takes two elements from lines and utilizes matchCoordinates to find matching lines
  • One function findMissingLine(lineA,desiredLine) that returns boolean if lineA is the same as desiredLine, here I would include the edgecase that e.g. element 3 in lines is both [10, 10, 200, 10] and [200, 10, 10, 10]
gqstav
  • 1,984
  • 1
  • 12
  • 18