0

i have an object with Vectors describing an polygon. It looks something like that:

enter image description here

Now i´m looking for an effective algorithm to remove the unnecessary vectors to get something like that:

enter image description here

Does anyone know an good way to do this?

Philipp Br
  • 113
  • 2
  • 7
  • 1
    Check out this question: http://stackoverflow.com/questions/3813681/checking-to-see-if-3-points-are-on-the-same-line You can check consecutive triplets and if they're on the same line, remove middle point/replace vectors with sum. – default locale Aug 11 '15 at 09:01
  • yes, this is what i want to do – Philipp Br Aug 11 '15 at 09:03
  • 2
    Here's what comes to mind off the top of my head: Sort by angle (normalized such that opposite directions end up treated the same), then, for each group of vectors sharing the same angle, sort by (x1,y1). Then in it would be easy (linear time) to check if any consecutive vectors in that list connect together. You merge it and continue searching. – VoidStar Aug 11 '15 at 09:04
  • thank you! this was very helpful – Philipp Br Aug 11 '15 at 09:04

1 Answers1

0

After some further research I wrote the following code as solution:

public void optimize() {
    if (vectors.size() < 3)
        return;

    for (int i = 2; i < vectors.size(); i++) {
        if (sameLine(vectors.get(i - 2),vectors.get(i - 1), vectors.get(i)))
            vectors.remove(--i);
    }
}

boolean sameLine(Point a, Point b , Point c) {
    if ((b.x < a.x && b.x < c.x)|| (b.x > c.x && b.x > a.x) || (b.y < a.y && b.y < c.y)|| (b.y > c.y && b.y > a.y))
        return false;
    return (a.y - b.y) * (a.x - c.x) == (a.y - c.y) * (a.x - b.x);
}

vector a ArrayList of point objects.

Philipp Br
  • 113
  • 2
  • 7