如何修改for循环:禁止首尾元素对比,允许其余元素与末尾元素对比
Got it, let's tweak your loop to match exactly what you need—preventing the first point from comparing with the last one, while letting all other points pair up with the final point without restrictions.
The Core Requirement Recap
- For the first point (
<1,1>in your example), only compare it with points in the middle (<99,99>,<199,1>) — never the last point (<210,99>). - For every other point (from the second one onward), allow comparisons with all subsequent points, including the last one.
Option 1: Adjust the Inner Loop's Upper Bound (Efficient)
This approach limits the inner loop's range upfront, avoiding unnecessary iterations:
for(int i = 0; i < this.points.size()-1; i++) { Point firstPoint = this.points.get(i); // Set the max index for j: skip last point only when i is the first element int jUpperLimit = (i == 0) ? this.points.size() - 2 : this.points.size() - 1; for(int j = i+1; j <= jUpperLimit; j++) { Point secondPoint = this.points.get(j); // Add your point comparison logic here } }
How It Works with Your Example
Your point list has 4 elements (indices 0 to 3):
- When
i=0(first point<1,1>),jUpperLimitbecomes4-2=2— sojruns from 1 to 2, pairing with<99,99>and<199,1>(no match with<210,99>). - When
i=1(second point<99,99>),jUpperLimitis3—jruns from 2 to 3, pairing with<199,1>and<210,99>. - When
i=2(third point<199,1>),jUpperLimitis3—jruns to 3, pairing with<210,99>.
Option 2: Skip the Unwanted Pair Explicitly (Readable)
If you prefer more straightforward logic, you can keep the original loop range and just skip the specific pair you don't want:
for(int i = 0; i < this.points.size()-1; i++) { Point firstPoint = this.points.get(i); for(int j = i+1; j < this.points.size(); j++) { // Skip the comparison between first and last point if (i == 0 && j == this.points.size() - 1) { continue; } Point secondPoint = this.points.get(j); // Add your point comparison logic here } }
This checks if we're trying to compare the first and last point, and skips that iteration entirely. It's easier to read at a glance, though it does one extra check per inner loop iteration.
Why This Fixes Your Issue
Both versions eliminate the implicit polygon closure you wanted to avoid, since the first and last points never get compared. All other valid pairs (including middle points with the last one) are still processed as needed.
内容的提问来源于stack exchange,提问作者Bob Doe

