0

Can anyone please help.

I have a problem where I need to loop through 3 lines and check if they are intersecting using C#. The 3 lines will make up the general shape of a triangle. Therefore, only 2 lines will ever be intersecting at a a time.

I have 3 Line objects and I have stored them in List lines. My method to check for intersections currently looks like this:

ProcessIntersections(lines[0], lines[1])
ProcessIntersections(lines[1], lines[2])
ProcessIntersections(lines[2], lines[0])

Looping through the list once I can do, but to check the final intersection, I have to pass in the first line again and check it against the last line.

Is there a better way to process my intersections? How would I be able to loop through the list of lines by only calling ProcessIntersections once? I tried:

for (int i = 0; i < lines.Count; i++)
{
    if (i >= 3)
    {
        i = 0;
        ProcessIntersection(lines[i], lines[i + 1]);
    }
}

But this just lands me in an infinite loop as i keeps on resetting to 0.

Does anyone have any suggestions.

2
  • Why is it an issue to call ProcessInteractions multiple times? If this method compares two lines for intersection then it does exactly what you want with your first code example. The whole point of creating methods is to be able to re-use the code and call it multiple times with different input Commented Mar 15, 2012 at 16:19
  • 1
    If you only have 3 lines then lines.Count = 3 --> this means that i will never be >= 3. Commented Mar 15, 2012 at 16:22

3 Answers 3

1

Try next loop:

for (int i = 0; i < lines.Count; i++)
{
  var next_i = i + 1;
  if (next_i >= lines.Count)
    next_i = 0;
  ProcessIntersection(lines[i], lines[next_i]);
}

or optimized loop:

for (int i = 0; i < lines.Count; i++)
{
  ProcessIntersection(lines[i], lines[(i + 1) % lines.Count]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to check each line with its successor and then the last line with lines[0], you could do this:

for(int i = 0;i < lines.Count - 1;++i)
    ProcessIntersection(lines[i], lines[i + 1]);
if(lines.Count > 1)
  ProcessIntersection(lines[lines.Count - 1], lines[0]);

If you really want it all handled in the for() loop (which would have a negative impact on speed) you could do this:

for(int i = 0;i < lines.Count;++i)
  ProcessIntersection(lines[i], lines[i == lines.Count - 1 ? 0 : i + 1]);

Comments

1
for (int i = 0; i < lines.Count; i++)
{
        ProcessIntersection(lines[i], lines[i == lines.Count -1 ? 0 : i + 1]);
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.