r/dailyprogrammer • u/Elite6809 1 1 • Apr 17 '14
[4/18/2014] Challenge #158 [Hard] Intersecting Rectangles
(Hard): Intersecting Rectangles
Computing the area of a single rectangle is extremely simple: width multiplied by height.
Computing the area of two rectangles is a little more challenging. They can either be separate and thus have their areas calculated individually, like this. They can also intersect, in which case you calculate their individual areas, and subtract the area of the intersection, like this.
Once you get to 3 rectangles, there are multiple possibilities: no intersections, one intersection of two rectangles, two intersections of two rectangles, or one intersection of three rectangles (plus three intersections of just two rectangles).
Obviously at that point it becomes impractical to account for each situation individually but it might be possible. But what about 4 rectangles? 5 rectangles? N rectangles?
Your challenge is, given any number of rectangles and their position/dimensions, find the area of the resultant overlapping (combined) shape.
Formal Inputs and Outputs
Input Description
On the console, you will be given a number N - this will represent how many rectangles you will receive. You will then be given co-ordinates describing opposite corners of N rectangles, in the form:
x1 y1 x2 y2Where the rectangle's opposite corners are the co-ordinates (x1, y1) and (x2, y2).
Note that the corners given will be the top-left and bottom-right co-ordinates, in that order. Assume top-left is (0, 0).
Output Description
You must print out the area (as a number) of the compound shape given. No units are necessary.
Sample Inputs & Outputs
Sample Input
(representing this situation)
3
0 1 3 3
2 2 6 4
1 0 3 5Sample Output
18Challenge
Challenge Input
18
1.6 1.2 7.9 3.1
1.2 1.6 3.4 7.2
2.6 11.6 6.8 14.0
9.6 1.2 11.4 7.5
9.6 1.7 14.1 2.8
12.8 2.7 14.0 7.9
2.3 8.8 2.6 13.4
1.9 4.4 7.2 5.4
10.1 6.9 12.9 7.6
6.0 10.0 7.8 12.3
9.4 9.3 10.9 12.6
1.9 9.7 7.5 10.5
9.4 4.9 13.5 5.9
10.6 9.8 13.4 11.0
9.6 12.3 14.5 12.8
1.5 6.8 8.0 8.0
6.3 4.7 7.7 7.0
13.0 10.9 14.0 14.5Challenge Output (hidden by default)
Notes
Thinking of each shape individually will only make this challenge harder. Try grouping intersecting shapes up, or calculating the area of regions of the shape at a time.
Allocating occupied points in a 2-D array would be the easy way out of doing this - however, this falls short when you have large shapes, or the points are not integer values. Try to come up with another way of doing it.
Because this a particularly challenging task, We'll be awarding medals to anyone who can submit a novel solution without using the above method.
5
u/Meshiest Apr 17 '14 edited Apr 18 '14
Ruby 242 bytes
Ruby 370 (works with floating point input)
2
u/skeeto -9 8 Apr 17 '14
I thought this sounded familiar: #95 hard. Yours isn't limited to integers, though, which makes it more challenging.
10
u/skeeto -9 8 Apr 18 '14 edited Apr 18 '14
C++11. Uses a sweep algorithm. It runs a vertical line left to right, visiting each point along the way and computing area based on intersection.
It spits out the correct result instantly for the sample inputs.
6
u/gspor Apr 18 '14
My first submission, using matlab which I'm most comfortable in
5
u/[deleted] Apr 18 '14
First post on this sub, here is my attempt in Haskell:
4
u/lasalvavida 0 1 Apr 18 '14
I solved this in Java using cell-shading. It's definitely not the most efficient algorithm, but I thought it was a novel approach. It creates a 2D boolean array of appropriate size and resolution to handle the points given. It then "shades" each rectangle on our boolean canvas. The shaded cells get counted up and multiplied by the area of a unit cell.
1
u/azvenigo Apr 21 '14
Am I missing something or is this remarkably simple?
The resultant area is the summation of the areas of all rectangles minus the area of every rectangle overlapping with every other.
1
u/darrellplank Jun 20 '14
c# - Okay - first submission to reddit so hopefully I won't screw it up.
I did a sweep algorithm but kept track of "strips" where a strip is a horizontal region currently covered in the sweep by some number of rectangles. Adjacent strips are covered by a different number of rectangles. The strips are kept in a sorted list so that finding the strip which contains a particular y position can be done through a binary search. The events of the sweep algorithm are of two types - leading edges or trailing edges of rectangles. This allows me to easily keep a running total length of all rects covering the sweep line. Multiplying that by the distance since the previous event gives me the area covered between the two events. Each strip has a count of the number of rectangles covering it. I start out with a strip covered by zero rectangles with y extent running from -infinity to +infinity. Whenever I get a leading edge I find the two strips that contain the top and bottom of the rectangle, split them if necessary to account for the new top/bottom and increment the coverage count for all the strips covered by the rectangle. If any of them go from 0 to 1 I add in their width to the current width. Removing rectangles is pretty much the opposite - lower the cover count on all strips covered by the rectangle and subtract out their width from the current width if the cover count goes to zero. Merge the top and bottom strips if their cover count matches the strips above/below them. I believe it should run in O(n log n). n log n to sort the events, log n to binary search the strips to find the ones which contain a rectangle and n to adjust the count for the new strips and keep the sorted array sorted properly for a total of n log n + log n + n = O(n log n)
1
u/Elite6809 1 1 Apr 17 '14 edited Apr 18 '14
My Ruby solution as usual. I decided to clean this up and make it more object-oriented. The benefit of this algorithm is speed; it computes the challenge input in around a millisecond.
2
u/OffPiste18 Apr 18 '14
Here's a simple Scala solution, with explanation:
First, a simple rectangle class. I happened to choose (x, y, w, h); using (x1, y1, x2, y2) would have worked just as well. The only slight-complex method just finds a new rectangle that is the intersection of two rectangles:
Next, we can use a fold along with the above intersection method to get the intersection of a list of rectangles:
Then there's a helper method to generate all subsets of a list of a given size. There are two base cases: there's only one subset (the empty set) of size 0. And there are no subsets with at least one element of an empty list. Then the recursion works as follows: For the head of the list, we can either include or exclude it. If we include it, we can find all subsets of size n-1 of the rest of the list, and add the head to those. If we exclude it, we just find all subsets of size n of the rest of the list. In code:
Now we have all the pieces to apply the Inclusion-Exclusion Principle to find the overall area. Its (sum of area of all rectangles) - (sum of area of intersections of pairs of rectangles) + (sum of area of intersections of three rectangles) - (area of intersection of four)... :
And lastly, a main method to do parsing and output an answer:
It's definitely not the most efficient algorithm; I'm sure those that know more than I about computational geometry will scoff at this. But it's simple and it works.
2
u/Ragingman2 Apr 18 '14
First time posting on this sub, so feel free to point anything out but please be nice :).
The code makes a grid out of all possible subsections then checks each one for occupancy.
(Java)
2
u/xpressrazor Apr 18 '14
I could only come up solution for integers.
2
u/koreth Apr 18 '14 edited Apr 19 '14
My solution in Clojure, with comments inline. Knowing very little computational geometry, I decided to split each rectangle up into sub-rectangles along each axis at all the X and Y coordinates where any rectangle's edges lie. Then it's just a matter of discarding the duplicate values (which I implicitly do by using a set rather than a list) and totaling up the areas of all the sub-rectangles in the set.
I'm still pretty new at Clojure so this may be non-idiomatic or needlessly convoluted in places; feedback welcome. I didn't go for maximum compactness here and instead tried to split it up into small simple functions.
2
u/myss Apr 19 '14
Does a sweeping line in two dimensions. Worst case complexity is O(n2) where all rectangles are overlapping in x direction, but it will get much faster if the rectangles are more evenly distributed.
Code for reading data is copied from skeeto.
2
u/[deleted] Apr 19 '14 edited Apr 19 '14
My first attempt in Python 3. I think /u/gspor used the same method in his/her solution, which was very nice!
1
u/mike_bolt Apr 18 '14 edited Apr 20 '14
This is my Java solution. It looks similar to the sweeping method.
It puts all left and right edges into a list sorted by x position, and all top and bottom edges into a list sorted by y position. From there it can slice off rectangular sections from the top. The whole thing is O(n2 ).
Edge.java
1
u/thecyberwraith Apr 18 '14
First time posting here, so let me know if I should format differently. I used Python and took the Inclusion-Exclusion route (so it took a few seconds to compute the challenge). Also, I knew that intersecting rectangles formed 9 possible intersecting regions that could be combined to a single rectangle, but I chose not to combine them.
1
u/flen_paris Apr 18 '14
Algorithms, Part 1 course in Coursera had a part about sweep algorithms for doing something similar as this.
1
u/gbromios Apr 18 '14
python, bruteforced by treating all axes as a grid on which to cut up all the rectangles, discarding duplicates. Just total the area of these rects and there's the answer. This isn't a particularly elegant solution, but it works.
edit: could probably have refactored the different horizontal/vertical functions into one, but I couldn't think of an reasonable way to do it... If anyone wants to critique me, that would be more helpful than looking at my medicore algorithm :P
1
u/pbeard_t 0 1 Apr 18 '14
C I spent the day outside and thought I was being clever when I recreated a sweep algorithm I vagely remember from algo. Then when I sat down to implement it I realized everyone did mostly the same thing... Anyway:
1
u/[deleted] Apr 18 '14 edited Jan 02 '16
1
u/KallDrexx Apr 19 '14
Well, this took longer than I thought it would. Not sure if that's a bad sign or what but I did do it without googling or looking up the sweep line algorithm (which apparently is the more efficient method based on comments).
Here's my solution in C# (minus the input parsing portions): https://gist.github.com/KallDrexx/11094250 (gist due to length).
Completes the challenge in 194ms, which is probably a lot (not sure though). I can probably make it more efficient by controlling the loops a bit better, and by more efficiently adding new corners instead of resorting each time (instead of relying on linq).
1
u/STOCHASTIC_LIFE 0 1 Apr 19 '14 edited Apr 19 '14
Here is my R solution. It traces a plot with the rectangles in red over the confining area (in blue). Then it applies the ratio of red pixels to the total area.
Sample plot
Challenge plot
1
u/Godde Apr 20 '14 edited Apr 21 '14
Good old C. Been admiring the linux linked list for a while, decided to get some practice.Two lists of rectangles are maintained, one for "to-be-checked", and one for solved. Rectangles are checked and removed from the former until it is empty. If there is overlap, new rectangles are created to match the non-overlapping shape. These are then reinserted into the "to-be-solved"-list to be checked again. If there is no overlap, the rectangle is moved to the "solved"-list.MASSIVELY improved version. No more linked lists, everything stored contiguously in memory. Can handle 100 000 random rectangles in about 2 seconds or less (Does best if very large rectangles show up early)
Rectangles are checked against known "solved" rectangles. If there is no overlap, the rectangle is added to the "solved" rectangles. If there is overlap, new rectangles are created and recursively checked.
1
u/zeroelixis Apr 20 '14
Here's something in Go, but I'm a an amateur with it. This solution works where there are only doubly intersecting rectangles but not triply or greater intersecting rectangles, I kind of got stuck at that point...
1
u/lukz 2 0 Apr 22 '14
vbscript
1
u/doubleagent03 Apr 22 '14
This sounds like a variation on Death Mountains (http://www.reddit.com/r/dailyprogrammer/comments/12csl5/10302012_challenge_109_difficult_death_mountains/)
1
u/that_how_it_be Apr 23 '14 edited Apr 23 '14
I'm a little late to the part as I've just discovered this sub yesterday. Here is my PHP submission.
The program maintains a list of non-intersecting rectangles. When an incoming rectangle intersects with an existing one, the intersection is cut away and the remaining region is split into 1 to 4 new rectangles. These subdivisions are checked against the remainder of the list, subdividing further if necessary. Any remaining sub divisions are added to the non-intersecting list.
My Big O is a little fuzzy these days; I think this is O(n) or O(n log n ).
If N were very large I think sub dividing the region defined by the rectangle coordinates and isolating rectangles into regions (and splitting across region boundaries) would be a reasonable approach. You could get really fancy and self balancing regions like you can with trees; how fun!
I also modified the input slightly.
This allows me to create one big input file with many tests and feed them to the program.
I'm a little sloppy with right margin; here is the Gist link
1
u/[deleted] Apr 23 '14 edited Apr 23 '14
Python solution. Keeps a list of rectangles to add to the area, and rectangles to subtract. Intersects each pair of rectangles given as input, and gets a list of rectangles representing the area it intersects with the other rectangles, and adds them to the list of rectangles to subtract. recursively calls the intersecting function on all the intersecting rectangles, and adds those to the adding list in order to not subtract the same space twice, then intersects those, etc.
1
u/UnchainedMundane 1 0 Apr 27 '14
My attempt (edit: Scala):
=
1
u/Puzzel May 17 '14 edited May 24 '14
Python 2 Solution.
Checks every cell in grid created by rectangle corners to see if covered. Then adds areas of all covered cells. See below:
Also outputs an image of the overlapped rectangles! DOES NOT USE THIS IMAGE IN CALCULATION OF AREA.
1
u/jeaton May 21 '14
Hackish solution in JavaScript:
0
u/[deleted] Apr 18 '14
[deleted] — view deleted comment
0
u/[deleted] Apr 19 '14
[deleted] — view deleted comment