Proposed optimisation for extra exercise 7
Review this proposal before applying it. The helper inserts it at the start of ClippedArea, before RectClip. Use only your assigned language.
cpp
if (!polygon.empty()) {
auto left = polygon.front().x;
auto top = polygon.front().y;
auto right = left;
auto bottom = top;
for (const auto& point : polygon) {
left = std::min(left, point.x);
top = std::min(top, point.y);
right = std::max(right, point.x);
bottom = std::max(bottom, point.y);
}
if (right <= clip.left || clip.right <= left ||
bottom <= clip.top || clip.bottom <= top) {
return 0.0;
}
if (left <= clip.left && top <= clip.top &&
right >= clip.right && bottom >= clip.bottom) {
return (static_cast<double>(clip.right) - clip.left) *
(static_cast<double>(clip.bottom) - clip.top);
}
}
csharp
if (polygon.Count > 0)
{
var left = polygon[0].X;
var top = polygon[0].Y;
var right = left;
var bottom = top;
foreach (var point in polygon)
{
left = Math.Min(left, point.X);
top = Math.Min(top, point.Y);
right = Math.Max(right, point.X);
bottom = Math.Max(bottom, point.Y);
}
if (right <= clip.left || clip.right <= left ||
bottom <= clip.top || clip.bottom <= top)
return 0.0;
if (left <= clip.left && top <= clip.top &&
right >= clip.right && bottom >= clip.bottom)
return (double)(clip.right - clip.left) * (clip.bottom - clip.top);
}