I've been searching far and wide on the seven internets, and have come to no avail. The closest to what I need seems to be The cutting stock problem, only in 2D (which is disappointing since Wikipedia doesn't provide any directions on how to solve that one). Another look-alike problem would be UV unwrapping. There are solutions there, but only those that you get from add-ons on various 3D software.
Cutting the long talk short - what I want is this: given a rectangle of known width and height, I have to find out how many shapes (polygons) of known sizes (which may be rotated at will) may I fit inside that rectangle.
For example, I could choose a T-shaped piece and in the same rectangle I could pack it both in an efficient way, resulting in 4 shapes per rectangle
as well as tiling them based on their bounding boxes, case in which I could only fit 3
But of course, this is only an example... and I don't think it would be much use to solving on this particular case. The only approaches I can think of right now are either like backtracking in their complexity or solve only particular cases of this problem. So... any ideas?
Anybody up for a game of Tetris (a subset of your problem)?
This is known as the packing problem. Without knowing what kind of shapes you are likely to face ahead of time, it can be very difficult if not impossible to come up with an algorithm that will give you the best answer. More than likely unless your polygons are "nice" polygons (circles, squares, equilateral triangles, etc.) you will probably have to settle for a heuristic that gives you the approximate best solution most of the time.
One general heuristic (though far from optimal depending on the shape of the input polygon) would be to simplify the problem by drawing a rectangle around the polygon so that the rectangle would be just big enough to cover the polygon. (As an example in the diagram below we draw a red rectangle around a blue polygon.)
Once we have done this, we can then take that rectangle and try to fit as many of that rectangle into the large rectangle as possible. This simplfies the problem into a rectangle packing problem which is easier to solve and wrap your head around. An example of an algorithm for this is at the following link:
An Effective Recursive Partitioning Approach for the Packing of Identical Rectangles in a Rectangle.
Now obviously this heuristic is not optimal when the polygon in question is not close to being the same shape as a rectangle, but it does give you a minimum baseline to work with especially if you don't have much knowledge of what your polygon will look like (or there is high variance in what the polygon will look like). Using this algorithm, it would fill up a large rectangle like so:
Here is the same image without the intermediate rectangles:
For the case of these T-shaped polygons, the heuristic is not the best it could be (in fact it may be almost a worst case scenario for this proposed approximation), but it would work very well for other types of polygons.
consider what the other answer said by placing the t's into a square, but instead of just leaving it as a square set the shapes up in a list. Then use True and False to fill the nested list as the shape i.e. [[True,True,True],[False,True,False]] for your T shape. Then use a function to place the shapes on the grid. To optimize the results, create a tracker which will pay attention to how many false in a new shape overlap with trues that are already on the grid from previous shapes. The function will place the shape in the place with the most overlaps. There will have to be modifications to create higher and higher optimizations, but that is the general premise which you are looking for.
Related
I want to programm a tool that can place objects on a rectangle with the minumum of waste, this problem is also known as the cutting problem.
So i looked around to find some algorithms and i found out there are a few for rectangles but not that much for n-edged polygones.
my first approach was to get a bounding box for the polygone, then run the normal rectangle algorithm. After that you cound slowly try to increase the number of edges but still have only isometric lines (only vertical and horizontal), to approximate the polygone.
I wonder if there is any good algorithm that implement such thing, but is more common than create my own stuff.
the other way ive come up with could be something with two dimensional knapsack and some sorting heuristics that sort the best fitting polygones and try to put them on the rectangle.
But all i come up with has some good detection of special polygones (such as a square or normal rectangle) but does not work on common polygones.
Given a collection of say, 50, images with various widths and heights, how would one go about programmatically arranging them in an interesting* abstract way? (see image below)
By interesting I mean, no large gaps, and no easily distinguishable rows or columns (negative space forms a lot of T-like intersections).
For my specific case, all images have a set max dimension of 150px, which could mean the height OR width is a max of 150px (could be 150px by 450px, or 378px by 150px).
This seems like it could be a classic programming challenge but I'm finding the topic hard to Google...
EDIT: Changed image to show that there is no restriction on how the overall arrangement must be (doesn't have to fit inside a set area)
If you are not opposed to jquery plugin, you can check this out - http://masonry.desandro.com/
Your problem is NP-Hard.
This thread shows that even with one type of nXm rectangles, it is NP-Hard to find if there is a solution , so your more generalized problem is of course NP-Hard as well [The only one type of rectangle is a private case of this problem]
You could try a backtracking solution if you are after optimized solution, or a heuristic approach such as genetic algorithms or hill climbing, which will be faster - but will usually find a non optimal result.
I have built something similar to this (although it is probably not the most sophisticated solution). My approach was to use a quadtree to organize the rectangles that I had placed on the canvas. I then just basically went around the center point in a spiral, trying to place new rectangles, and using the quadtree to detect collisions. If I detected a collision then I would move the rectangle I was trying to place to the edge of the rectangle that it collided with that was furthest from the center and repeat the collision checking process.
Again, probably not the most sophisticated method, and it does tend to leave some larger gaps between rectangles (the borders between them are not uniform), but to my taste it gave good results.
I'm trying to render polygons, but they can only be rendered using axis-aligned rectangles. So, I' looking for an algorithm that can basically fill in a polygon using the least possible amount of rectangles. If it helps reduce the amount, the rectangles are allowed to overlap each other.
I've already implemented this fill algorithm, which mostly suffices. The downfall is that it restricts rectangles to each pixel row. I ultimately want to reduce the amount of rectangles as much as possible.
Pixel representation of polygon is same as rectilinear polygon and you can partition it quite fast. See answer to this question.
Removing that restriction (that each rectangle have a height of one pixel) helps in some special cases when the polygon is made of big rectangles, but not at all in the general case.
How about this: use that algorithm, but extend each rectangle upward and downward as much as you can, and when all of the rectangles are in place, eliminate redundant ones.
There is still a little bit of room for improvement, in that the order in which you eliminate redundant rectangles might matter in some very rare cases, but honestly I don't think it's worth worrying about for a practical solution.
I have polygons that define the contour of counties in the UK. These shapes are very detailed (10k to 20k points each), thus rendering the related computations (is point X in polygon P?) quite computationaly expensive.
Thus, I would like to "subsample" my polygons, to obtain a similar shape but with less points. What are the different techniques to do so?
The trivial one would be to take one every N points (thus subsampling by a factor N), but this feels too "crude". I would rather do some averaging of points, or something of that flavor. Any pointer?
Two solutions spring to mind:
1) since the map of the UK is reasonably squarish, you could choose to render a bitmap with the counties. Assign each a specific colour, and then render the borders with a 1 or 2 pixel thick black line. This means you'll only have to perform the expensive interior/exterior calculation if a sample happens to lie on the border. The larger the bitmap, the less often this will happen.
2) simplify the county outlines. You can use a recursive Ramer–Douglas–Peucker algorithm to recursively simplify the boundaries. Just make sure you cache the results. You may also have to solve this not for entire county boundaries but for shared boundaries only, to ensure no gaps. This might be quite tricky.
Here you can find a project dealing exactly with your issues. Although it works primarily with an area "filled" by points, you can set it to work with a "perimeter" type definition as yours.
It uses a k-nearest neighbors approach for calculating the region.
Samples:
Here you can request a copy of the paper.
Seemingly they planned to offer an online service for requesting calculations, but I didn't test it, and probably it isn't running.
HTH!
Polygon triangulation should help here. You'll still have to check many polygons, but these are triangles now, so they are easier to check and you can use some optimizations to determine only a small subset of polygons to check for a given region or point.
As it seems you have all the algorithms you need for polygons, not only for triangles, you can also merge several triangles that are too small after triangulation or if triangle count gets too high.
I'm looking for a packing algorithm which will reduce an irregular polygon into rectangles and right triangles. The algorithm should attempt to use as few such shapes as possible and should be relatively easy to implement (given the difficulty of the challenge). It should also prefer rectangles over triangles where possible.
If possible, the answer to this question should explain the general heuristics used in the suggested algorithm.
This should run in deterministic time for irregular polygons with less than 100 vertices.
The goal is to produce a "sensible" breakdown of the irregular polygon for a layman.
The first heuristic applied to the solution will determine if the polygon is regular or irregular. In the case of a regular polygon, we will use the approach outlined in my similar post about regular polys: Efficient Packing Algorithm for Regular Polygons
alt text http://img401.imageshack.us/img401/6551/samplebj.jpg
I don't know if this would give the optimal answer, but it would at least give an answer:
Compute a Delaunay triangulation for the given polygon. There are standard algorithms to do this which will run very quickly for 100 vertices or fewer (see, for example, this library here.) Using a Delaunay triangulation should ensure that you don't have too many long, thin triangles.
Divide any non-right triangles into two right triangles by dropping an altitude from the largest angle to the opposite side.
Search for triangles that you can combine into rectangles: any two congruent right triangles (not mirror images) which share a hypotenuse. I suspect there won't be too many of these in the general case unless your irregular polygon had a lot of right angles to begin with.
I realize that's a lot of detail to fill in, but I think starting with a Delaunay triangulation is probably the way to go. Delaunay triangulations in the plane can be computed efficiently and they generally look quite "natural".
EDITED TO ADD: since we're in ad-hoc heuristicville, in addition to the greedy algorithms being discussed in other answers you should also consider some kind of divide and conquer strategy. If the shape is non-convex like your example, divide it into convex shapes by repeatedly cutting from a reflex vertex to another vertex in a way that comes as close to bisecting the reflex angle as possible. Once you've divided the shape into convex pieces, I'd consider next dividing the convex pieces into pieces with nice "bases", pieces with at least one side having two acute or right angles at its ends. If any piece doesn't have such a "base" you should be able to divide it in two along a diameter of the piece, and get two new pieces which each have a "base" (I think). This should reduce the problem to dealing with convex polygons which are kinda-sorta trapezoidal, and from there a greedy algorithm should do well. I think this algorithm will subdivide the original shape in a fairly natural way until you get to the kinda-sorta trapezoidal pieces.
I wish I had time to play with this, because it sounds like a really fun problem!
My first thought (from looking at your diagram above) would be to look for 2 adjacent right angles turning the same direction. I'm sure that won't catch every case where a rectangle will help, but from a user's point of view, it's an obvious case (square corners on the outside = this ought to be a rectangle).
Once you've found an adjacent pair of right angles, take the length of the shorter leg, and there's one rectangle. Subtract this from the polygon left to tile, and repeat. When there's no more obvious external rectangles to remove, then do your normal tiling thing (Peter's answer sounds great) on that.
Disclaimer: I'm no expert on this, and I haven't even tried it...