Solve day 9 part 2 using a sweep line algorithm #16
+125
−60
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a general implementation of 2025 day 9, part 2, that works on arbitrary valid inputs (including the example input) and does not exploit the giant "notch" that many other faster implementation depend on.
It is an 18-times speed up; the existing implementation on my machine takes:
This new sweep line implementation takes:
It works by a sweep line algorithm, scanning an imaginary horizontal line from top to bottom, processing red tiles that fall on this line, in left to right order.
As it scans, it calculates which intervals on the imaginary line are within the tiled region (that is, it determines the intersection of the sweep line and the tiled region, which is a set of intervals of x-coordinates).
After determining these intervals, the red tiles on the sweep line within these intervals are added to a list of candidate tiles (the tiles that could be the top left or right tile of a rectangle). The maximum left and right extent of any rectangle that could be made with this tile are also tracked, and as the sweep line moves down and edges and corners cut into this extent, it is reduced. Candidates whose extents become empty are removed from the candidate list.
In this way, only about 200 red tile "Candidate"s at most are being tracked during the sweep, and the list of descending edges never exceeds 8 edges on my input.
As per CONTRIBUTING.md, I agree that I have authored 100% of the content, that I have the necessary rights to the content and that the content I am contributing is provided under the project license. The code was formatted with
rustfmtandclippyhas no warnings.