I have N scalable square tiles (buttons) that need to be placed inside of fixed sized rectangular surface (toolbox). I would like to present the buttons all at the same size.
How could I solve for the optimal size of the tiles that would provide the largest area of the rectangular surface being covered by tiles.
Let W and H be the width and height of the rectangle.
Let s be the length of the side of a square.
Then the number of squares n(s) that you can fit into the rectangle is floor(W/s)*floor(H/s). You want to find the maximum value of s for which n(s) >= N
If you plot the number of squares against s you will get a piecewise constant function. The discontinuities are at the values W/i and H/j, where i and j run through the positive integers.
You want to find the smallest i for which n(W/i) >= N, and similarly the smallest j for which n(H/j) >= N. Call these smallest values i_min and j_min. Then the largest of W/i_min and H/j_min is the s that you want.
I.e. s_max = max(W/i_min,H/j_min)
To find i_min and j_min, just do a brute force search: for each, start from 1, test, and increment.
In the event that N is very large, it may be distasteful to search the i's and j's starting from 1 (although it is hard to imagine that there will be any noticeable difference in performance). In this case, we can estimate the starting values as follows. First, a ballpark estimate of the area of a tile is W*H/N, corresponding to a side of sqrt(W*H/N). If W/i <= sqrt(W*H/N), then i >= ceil(W*sqrt(N/(W*H))), similarly j >= ceil(H*sqrt(N/(W*H)))
So, rather than start the loops at i=1 and j=1, we can start them at i = ceil(sqrt(N*W/H)) and j = ceil(sqrt(N*H/W))). And OP suggests that round works better than ceil -- at worst an extra iteration.
Here's the algorithm spelled out in C++:
#include <math.h>
#include <algorithm>
// find optimal (largest) tile size for which
// at least N tiles fit in WxH rectangle
double optimal_size (double W, double H, int N)
{
int i_min, j_min ; // minimum values for which you get at least N tiles
for (int i=round(sqrt(N*W/H)) ; ; i++) {
if (i*floor(H*i/W) >= N) {
i_min = i ;
break ;
}
}
for (int j=round(sqrt(N*H/W)) ; ; j++) {
if (floor(W*j/H)*j >= N) {
j_min = j ;
break ;
}
}
return std::max (W/i_min, H/j_min) ;
}
The above is written for clarity. The code can be tightened up considerably as follows:
double optimal_size (double W, double H, int N)
{
int i,j ;
for (i = round(sqrt(N*W/H)) ; i*floor(H*i/W) < N ; i++){}
for (j = round(sqrt(N*H/W)) ; floor(W*j/H)*j < N ; j++){}
return std::max (W/i, H/j) ;
}
I believe this can be solved as a constrained minimisation problem, which requires some basic calculus. .
Definitions:
a, l -> rectangle sides
k -> number of squares
s -> side of the squares
You have to minimise the function:
f[s]:= a * l/s^2 - k
subject to the constraints:
IntegerPart[a/s] IntegerPart[l/s] - k >= 0
s > 0
I programed a little Mathematica function to do the trick
f[a_, l_, k_] := NMinimize[{a l/s^2 - k ,
IntegerPart[a/s] IntegerPart[l/s] - k >= 0,
s > 0},
{s}]
Easy to read since the equations are the same as above.
Using this function I made up a table for allocating 6 squares
as far as I can see, the results are correct.
As I said, you may use a standard calculus package for your environment, or you may also develop your own minimisation algorithm and programs. Ring the bell if you decide for the last option and I'll provide a few good pointers.
HTH!
Edit
Just for fun I made a plot with the results.
And for 31 tiles:
Edit 2: Characteristic Parameters
The problem has three characteristic parameters:
The Resulting Size of the tiles
The Number of Tiles
The ratio l/a of the enclosing rectangle
Perhaps the last one may result somewhat surprising, but it is easy to understand: if you have a problem with a 7x5 rectangle and 6 tiles to place, looking in the above table, the size of the squares will be 2.33. Now, if you have a 70x50 rectangle, obviously the resulting tiles will be 23.33, scaling isometrically with the problem.
So, we can take those three parameters and construct a 3D plot of their relationship, and eventually match the curve with some function easier to calculate (using least squares for example or computing iso-value regions).
Anyway, the resulting scaled plot is:
I realize this is an old thread but I recently solved this problem in a way that I think is efficient and always gives the correct answer. It is designed to maintain a given aspect ratio. If you wish for the children(buttons in this case) to be square just use an aspect ratio of 1. I am currently using this algorithm in a few places and it works great.
double VerticalScale; // for the vertical scalar: uses the lowbound number of columns
double HorizontalScale;// horizontal scalar: uses the highbound number of columns
double numColumns; // the exact number of columns that would maximize area
double highNumRows; // number of rows calculated using the upper bound columns
double lowNumRows; // number of rows calculated using the lower bound columns
double lowBoundColumns; // floor value of the estimated number of columns found
double highBoundColumns; // ceiling value of the the estimated number of columns found
Size rectangleSize = new Size(); // rectangle size will be used as a default value that is the exact aspect ratio desired.
//
// Aspect Ratio = h / w
// where h is the height of the child and w is the width
//
// the numerator will be the aspect ratio and the denominator will always be one
// if you want it to be square just use an aspect ratio of 1
rectangleSize.Width = desiredAspectRatio;
rectangleSize.Height = 1;
// estimate of the number of columns useing the formula:
// n * W * h
// columns = SquareRoot( ------------- )
// H * w
//
// Where n is the number of items, W is the width of the parent, H is the height of the parent,
// h is the height of the child, and w is the width of the child
numColumns = Math.Sqrt( (numRectangles * rectangleSize.Height * parentSize.Width) / (parentSize.Height * rectangleSize.Width) );
lowBoundColumns = Math.Floor(numColumns);
highBoundColumns = Math.Ceiling(numColumns);
// The number of rows is determined by finding the floor of the number of children divided by the columns
lowNumRows = Math.Ceiling(numRectangles / lowBoundColumns);
highNumRows = Math.Ceiling(numRectangles / highBoundColumns);
// Vertical Scale is what you multiply the vertical size of the child to find the expected area if you were to find
// the size of the rectangle by maximizing by rows
//
// H
// Vertical Scale = ----------
// R * h
//
// Where H is the height of the parent, R is the number of rows, and h is the height of the child
//
VerticalScale = parentSize.Height / lowNumRows * rectangleSize.Height;
//Horizontal Scale is what you multiply the horizintale size of the child to find the expected area if you were to find
// the size of the rectangle by maximizing by columns
//
// W
// Vertical Scale = ----------
// c * w
//
//Where W is the width of the parent, c is the number of columns, and w is the width of the child
HorizontalScale = parentSize.Width / (highBoundColumns * rectangleSize.Width);
// The Max areas are what is used to determine if we should maximize over rows or columns
// The areas are found by multiplying the scale by the appropriate height or width and finding the area after the scale
//
// Horizontal Area = Sh * w * ( (Sh * w) / A )
//
// where Sh is the horizontal scale, w is the width of the child, and A is the aspect ratio of the child
//
double MaxHorizontalArea = (HorizontalScale * rectangleSize.Width) * ((HorizontalScale * rectangleSize.Width) / desiredAspectRatio);
//
//
// Vertical Area = Sv * h * (Sv * h) * A
// Where Sv isthe vertical scale, h is the height of the child, and A is the aspect ratio of the child
//
double MaxVerticalArea = (VerticalScale * rectangleSize.Height) * ((VerticalScale * rectangleSize.Height) * desiredAspectRatio);
if (MaxHorizontalArea >= MaxVerticalArea ) // the horizontal are is greater than the max area then we maximize by columns
{
// the width is determined by dividing the parent's width by the estimated number of columns
// this calculation will work for NEARLY all of the horizontal cases with only a few exceptions
newSize.Width = parentSize.Width / highBoundColumns; // we use highBoundColumns because that's what is used for the Horizontal
newSize.Height = newSize.Width / desiredAspectRatio; // A = w/h or h= w/A
// In the cases that is doesnt work it is because the height of the new items is greater than the
// height of the parents. this only happens when transitioning to putting all the objects into
// only one row
if (newSize.Height * Math.Ceiling(numRectangles / highBoundColumns) > parentSize.Height)
{
//in this case the best solution is usually to maximize by rows instead
double newHeight = parentSize.Height / highNumRows;
double newWidth = newHeight * desiredAspectRatio;
// However this doesn't always work because in one specific case the number of rows is more than actually needed
// and the width of the objects end up being smaller than the size of the parent because we don't have enough
// columns
if (newWidth * numRectangles < parentSize.Width)
{
//When this is the case the best idea is to maximize over columns again but increment the columns by one
//This takes care of it for most cases for when this happens.
newWidth = parentSize.Width / Math.Ceiling(numColumns++);
newHeight = newWidth / desiredAspectRatio;
// in order to make sure the rectangles don't go over bounds we
// increment the number of columns until it is under bounds again.
while (newWidth * numRectangles > parentSize.Width)
{
newWidth = parentSize.Width / Math.Ceiling(numColumns++);
newHeight = newWidth / desiredAspectRatio;
}
// however after doing this it is possible to have the height too small.
// this will only happen if there is one row of objects. so the solution is to make the objects'
// height equal to the height of their parent
if (newHeight > parentSize.Height)
{
newHeight = parentSize.Height;
newWidth = newHeight * desiredAspectRatio;
}
}
// if we have a lot of added items occaisionally the previous checks will come very close to maximizing both columns and rows
// what happens in this case is that neither end up maximized
// because we don't know what set of rows and columns were used to get us to where we are
// we must recalculate them with the current measurements
double currentCols = Math.Floor(parentSize.Width / newWidth);
double currentRows = Math.Ceiling(numRectangles/currentCols);
// now we check and see if neither the rows or columns are maximized
if ( (newWidth * currentCols ) < parentSize.Width && ( newHeight * Math.Ceiling(numRectangles/currentCols) ) < parentSize.Height)
{
// maximize by columns first
newWidth = parentSize.Width / currentCols;
newHeight = newSize.Width / desiredAspectRatio;
// if the columns are over their bounds, then maximized by the columns instead
if (newHeight * Math.Ceiling(numRectangles / currentCols) > parentSize.Height)
{
newHeight = parentSize.Height / currentRows;
newWidth = newHeight * desiredAspectRatio;
}
}
// finally we have the height of the objects as maximized using columns
newSize.Height = newHeight;
newSize.Width = newWidth;
}
}
else
{
//Here we use the vertical scale. We determine the height of the objects based upong
// the estimated number of rows.
// This work for all known cases
newSize.Height = parentSize.Height / lowNumRows;
newSize.Width = newSize.Height * desiredAspectRatio;
}
At the end of the algorithm 'newSize' holds the appropriate size. This is written in C# but it would be fairly easy to port to other languages.
The first, very rough heuristic is to take
s = floor( sqrt( (X x Y) / N) )
where s is the button-side-length, X and Y are the width and height of the toolbox, and N is the number of buttons.
In this case, s will be the MAXIMUM possible side-length. It is not necessarily possible to map this set of buttons onto the toolbar, however.
Imagine a toolbar that is 20 units by 1 unit with 5 buttons. The heuristic will give you a side length of 2 (area of 4), with a total covering area of 20. However, half of each button will be outside of the toolbar.
I would take an iterative approach here.
I would check if it is possible to fit all button in a single row.
If not, check if it is possible to fit in two rows, and so on.
Say W is the smaller side of the toolbox.
H is the other side.
For each iteration, I would check for the best and worst possible cases, in that order. Best case means, say it is the nth iteration, would try a size of W/n X W/n sized buttons. If h value is enough then we are done. If not, the worst case is to try (W/(n+1))+1 X (W/(n+1))+1 sized buttons. If it is possible to fit all buttons, then i would try a bisection method between W/n and (W/(n+1))+1. If not iteration continues at n+1.
Let n(s) be the number of squares that can fit and s their side. Let W, H be the sides of the rectangle to fill. Then n(s) = floor(W/s)* floor(H/s). This is a monotonically decreasing function in s and also piecewise constant, so you can perform a slight modification of binary search to find the smallest s such that n(s) >= N but n(s+eps) < N. You start with an upper and lower bound on s u = min(W, H) and l = floor(min(W,H)/N) then compute t = (u + l) / 2. If n(t) >= N
then l = min(W/floor(W/t), H/floor(H/t)) otherwise u = max(W/floor(W/t), H/floor(H/t)). Stop when u and l stay the same in consecutive iterations.
So it's like binary search, but you exploit the fact that the function is piecewise constant and the change points are when W or H are an exact multiple of s. Nice little problem, thanks for proposing it.
We know that any optimal solution (there may be two) will fill the rectangle either horizontally or vertically. If you found an optimal solution that did not fill the rectangle in one dimension, you could always increase the scale of the tiles to fill one dimension.
Now, any solution that maximizes the surface covered will have an aspect ratio close to the aspect ratio of the rectangle. The aspect ratio of the solution is vertical tile count/horizontal tile count (and the aspect ratio of the rectangle is Y/X).
You can simplify the problem by forcing Y>=X; in other words, if X>Y, transpose the rectangle. This allows you to only think about aspect ratios >= 1, as long as you remember to transpose the solution back.
Once you've calculated the aspect ratio, you want to find solutions to the problem of V/H ~= Y/X, where V is the vertical tile count and H is the horizontal tile count. You will find up to three solutions: the closest V/H to Y/X and V+1, V-1. At that point, just calculate the coverage based on the scale using V and H and take the maximum (there could be more than one).
Related
Can't invent something acceptable.
My first (and sole) approach is pretty awkward:
Calculate area = non_rounded_area + area_of_rounded corner * 4. Let's consider this area as pixel count in the rect.
Get random number from range [0..area), so to say a pixel index.
Somehow get x and y coordinates from that index.
The main embarrassment is how to perform step 3?
I reckon it's even enough to consider 1/4 part of rect (and one corner) and just rotate result for other quarters.
Ok, suppose I know what number of pixels belongs' to the given corner.
And it's easy to get x and y coordinates from index that belongs to non-rounded area.
But how to do this for pixels that belongs to corners?
My thoughts are flying about "determine whether pixel belongs to circle" but can't formulate them plainly.
Here's a way to do it for one quadrant that you can generalize to a full rectangle:
First compute the total number of pixels in the quadrant (red + orange + green):
int totalPixels = w * h;
Then compute the red area (the pixels in the corner that are outside the rounded rect):
int invalidCornerPixels = (int)((float)(r * r) * ((4.0f - PI) / 4.0f));
The orange area is equal to the red area. You can sample pixels in the red + green area, and if they are in the red area, sample a random pixel in the orange area instead.
int redGreenArea = totalPixels - invalidCornerPixels;
Assume randomValue(n) returns a random int from 0 to n - 1:
int pixelIndex = randomValue(redGreenArea);
int pixelX = pixelIndex % w;
int pixelY = pixelIndex / w;
Test if the sampled pixel is in the red area and resample if necessary:
if((pixelX < r) && (pixelY < r))
{
int circleX = r - pixelX;
int circleY = r - pixelY;
if(((circleX * circleX) + (circleY * circleY)) > (r * r))
{
pixelIndex = randomValue(invalidCornerPixels) + redGreenArea;
pixelX = pixelIndex % w;
pixelY = pixelIndex / w;
}
}
This requires a maximum of 2 random number generations (usually only 1), and isn't any more complicated than rejection sampling, because you have to implement the same test for that too. The calculation of totalPixels, invalidCornerPixels and redGreenArea can be done once and stored for a given rectangle.
One weakness is that due to rounding errors the number of pixels that will fail the test in practice may not be exactly equal to invalidCornerPixels, which will give a very slightly non-uniform distribution. You could address this by calculating invalidCornerPixels by brute force offline (counting the pixels that fail the test in an r x r square) and creating a lookup table for each value of r. I doubt it will be noticeable if used for a particle generator however. Another weakness is that it will fail if the red area overlaps the orange area.
I have a circle which i need to fill with rectangles.Piled one over the other.The rectangles are available in specific sizes only.And we are also given the number of rectangles we must put.I need to get the set of rectangle lengths which cover the most area of the circle.For eg if the circle has a diameter of 100,rectangles of lengths [100,95,90,85,...15,10,5] can be put.I have tried using a brute force method by parsing through all the possible combinations.It yields good results when the numbers are small.Another algorithm i tried is to restrict the range of lengths which each rectangle occupies.Like the first rectangle will have a length of 95 or 90 to give the best result.But even this method is cumbersome when the number of rectangles to be put is really high.Here is how the rectangles are arranged
If the first rectangle has a length l,and diameter of circle is d,its thickness is sqrt(d2-l2).The thickness of second one if its length is k is sqrt(d2-k2)-sqrt(d2-l2).
Is there any algorithm so that i can go formulate the results.
Why should a brute-force-attack on this problem be difficult? You just need to put some effort in your calculation code and I'm sure it will work fine. It just has 19 levels at maximum. This shouldn't be too complicated and will give you the result within ... well, some hours, as I just found out. 19 levels will result in 3.3e17 calculations.
About the algorithm:
With one rectangle, you get the largest covered area when the rectangle is a square. I think that's very easy to understand. The corner of the square is at 45° from the circle center (assuming that horizontal is 0°, but that actually doesn't matter as the whole structre is point symmetric), the size is (0.707*diameter)^2 = 5000.
The closest to width 70.7 is 70. In general I suggest checking the number below (70) and above (75) the accurate result (70.7). The area of your rectangle is 70 * 71.41 = 4999. (But it would be nice to know, if the height also has to be a value out of your 5's-grid!)
Now it's getting more difficult and I hope I am right:
As I write this answer, it turns out, I am not right. :-( The rounded values have a higher result than the theoretical maximum. But I will post it regardless, maybe it helps to find the real answer.
When you have 2 rectangles, the largest area to cover should be when
the corners of rect1 are at 30° (and 150°, 210°, 330°), and
the corners of rect2 are at 60° (and 120°, 240°, 300°).
The sizes would be:
rect 1: 0.866*dia * 0.5 *dia = 4330
rect 2: 0.5 *dia * 0.866*dia = 4330 - minus the overlap =>> 0.5*0.36*dia^2 = 1830
sum: 6160
rounded to the 5's grid:
rect 1, #1) 85*52.86 = 4478
rect 2: #1) 50*(86.60-52.86) = 1696.2 #2) 55*(83.52-52.86) = 1696.1 #3) 45*(89.30-52.86) = 1648
sums: 6173.87 // 6173.75 // 6126
rect 1, #2) 90*43.59 = 3923
rect 2: #1) 50*(86.60-43.59) = 2151 #2) 55*(83.52-43.59) = 2196 #3) 45*(89.30-43.59) = 2057
sums: 6074 // 6119 // 5980
The winner is combination 1.1: rect1 = 85, rect2 = 50.
Due to using rounded values, you have to check each combination of upper and lower (and exact if it is on the grid) value of each rectangle, resulting in a maximum of 3^n checks if n is the number of rectangles (except n=1). A brute force is not nicer, but maybe easier. (And as found out and written above, it maybe will return better results, as this method is inaccurate).
EDIT 1:
The formula for 1 rectangle (which results in a square) is:
A = x * sqrt(D²-x²)
calculate the maximum using the derivative of A:
A' = D²-2x² / sqrt(D²-x²) = 0
You can also find it here: http://oregonstate.edu/instruct/mth251/cq/Stage8/Lesson/rectangle.html
The formula for 2 rectangles is:
A = f(x,y) = x * sqrt(D²-x²) + y * [sqrt(D²-y²)-sqrt(D²-x²)]
( x = width of r1, y = width of r2 )
The formula for n rectangles depends on n unknown variables. So you need to calculate n partial derivatives. Have fun! (or consider brute force, as you already are given a grid and don't need to do iterations ;-) )
Brute force algorithm
amount of calculations:
levels calculations
1 19
2 19 + 19*18 = 361
...
5 19 + 19*18 + 19*18*17 + 19*18*17*16 + 19*18*17*16*15 = 1494559
...
10 3.7e11
15 6.3e15
19 3.3e19
C# (or C++):
double dDia = 100;
int nSizes = 20;
int nmax = 2; // number of rectangles
int main()
{
int n = 1;
double dArea = 0.0;
dArea = CalcMaxArea (n, 0);
}
double CalcMaxArea (int n, double dSizeYParent)
{
double dArea = 0.0;
double dAreaMax = 0.0;
for (int iRun = nSizes-n; iRun >= 1; iRun--)
{
double dSizeX = iRun * 5;
double dSizeY = Math.Sqrt(dDia * dDia - dSizeX * dSizeX) - dSizeYParent);
double dAreaThis = dSizeX * dSizeY;
double dAreaOthers = 0.0;
if (n < nmax)
dAreaOthers = CalcMaxArea (n+1, dSizeY);
if (dArea > dAreaMax)
dAreaMax = dArea;
}
}
VBA, to be used in MS Excel
Dim dDia As Double
Dim nmax As Integer
Dim nSizes As Integer
Sub main()
dDia = 100
nmax = 2
nSizes = 20
Dim n As Integer
Dim dArea As Double
n = 1
dArea = CalcMaxArea(n, 0)
End Sub
Function CalcMaxArea(n As Integer, dSizeYParent As Double) As Double
Dim dArea As Double
Dim dAreaMax As Double
dArea = 0
For iRun = nSizes - n To 1 Step -1
Dim dSizeX As Double
Dim dSizeY As Double
Dim dAreaThis As Double
Dim dAreaOthers As Double
dSizeX = iRun * 5
dSizeY = Sqr(dDia * dDia - dSizeX * dSizeX) - dSizeYParent
dAreaThis = dSizeX * dSizeY
dAreaOthers = 0
If n < nmax Then
dAreaOthers = CalcMaxArea(n + 1, dSizeY)
End If
dArea = dAreaThis + dAreaOthers
If dArea > dAreaMax Then
dAreaMax = dArea
End If
Next
CalcMaxArea = dAreaMax
End Function
Tested in VBA with the given values, got the same result: 6173.87.
Further code may be added to remember on which values the maximum as reached.
I read the question again, and realize I completely missed a couple of key points in your post. The picture confused me, but that isn't a good excuse. My previous suggestion in the comments was a completely bad idea. I'm sorry, and I hope you didn't send a lot of time looking into it. If I had to solve this problem, this is how I would do it, right or wrong.
So I have been thinking this problem over. The best solution I can think of is to use a search algorithm such as A*. A* its self it rather simple to implement. I'm assuming you already have a method to calculate the area, which to me seems the hardest part. I have an idea of how I would go on with calculating the area of overlapping rectangles, but its the reason why I didn't write a program that could prove that my suggestion is a good one.
What I would do is have a master list of all of the potential rectangles.
Add to your frontier a copy of all rectangles not in the current path as the nth rectangle placed. This will allow you to set the width, and therefore calculate the area of the circle left to be filled. Keeping doing this, selecting the lowest cost path from the frontier each time, and after m nodes are explored, you should have the best fit. Where m is the total number of rectangles you must place.
For the cost evaluation, using the amount of space left to fill seems a natural choice. One thing to make note of though, is that the area left decreases over time, and you will need one that increases. I would think dividing the area left by the number of rectangles left should give you a nice cost function for finding the lowest cost path to the least area left in the circle. That one sounded good to me, but i'm sure there are others that could be used.
In regards to the heuristic, without a heuristic function you still have a best first search, so I would expect it to perform better than a blind brute force technique. With a good heuristic function, I would expect the performance to increase significantly. In thinking about what would make a good heuristic function, I thought that estimating the amount of the circle the rectangle would fill might work well. For instance, 10% of the area of the rectangle divided by the number of rectangles left to be placed. Since there is no pre-determined goal state, any estimate would have to be base solely off the area of the next rectangle. We know the full area of the rectangle won't contribute to solution. The majority of every rectangle after the first is wasted space as far as the solution goes, which is how i came up with that heuristic. As with the cost function, it seems like a reasonable idea to me, but if anyone can think of a better one, all the better.
There are all sorts of sites on A* out there, but here is one that looks well written. http://web.mit.edu/eranki/www/tutorials/search/
I hope this helps you out.
I know devising a working algorithm is complex, but this is the approach I thought of :
There could be only one rectangle which can occupy the maximum area in the circle with given diameter.
Find out the the Max width and height of rectangle that can be made to fit into the circle. There are a lot of solutions for the same. For example look: Find Largest Inscribed Rectangle This rectangle will then conclude a major portion of the max area.
The next task is then to fill the remaining portion of the circle with the rectangle of different sizes. Find out the best fit rectangle, as in the below image. This can be done by checking if the circle points lie inside the rectangle for a specified height and width
I again agree that this is very difficult to implement.
The problem states that I have a big rectangle, with dimension L and W, and unlimited number of identical small rectangles, with dimension l and w. L * W is guaranteed to be larger than l *w. So I want to find out the maximum number of small rectangles that I can put into the big rectangle, without overlapping. You can put the small rectangles in any orientation you like.
Axis Aligned
Rectangles fit best when they are tiled, with no space between. So, an outline of how to do it:
First, figure out how many fit if you just tile them in:
lFit = L / l // integer division for these, no remainder
wFit = W / w
You know that you can fit lFit * wFit rectangles inside if you stack them in the same orientation as the big rectangle. Check again with the other orientation, and choose the bigger one as your base.
Now you may have some space left over. That space is made up of rectangles. You can easily find the size of these from the previous step. Run it again for these smaller rectangles and add to the base number. Recurse until no more fit.
If no tiles will fit into the "remaining" smaller rectangle, it's time to check for tilted ones.
Diagonal
Once your tile does not fit axis-aligned into the rectangle, you need to tilt it. You can pack the most tiles in by tilting them just enough to fit in the longest box dimension, and placing it firmly against three walls. Then you try stacking more in below it.
Note: for all the math here, I'm using width as the "longest edge". If your rectangle/tile doesn't match, just flip the dimensions.
To figure out what the proper rotation angle is, you can use a trial/error binary search. I'm sure there's a more "mathy" way to do it, but this works well enough. The formula for the bounding width of a rotated rectangle is(angle in radians):
width = w * cos(angle) + h * sin(angle)
To do a trial/error, just loop it until you reach your tolerance:
// boxWidth, tileWidth, tileHeight
public static double getAngle(double bw, double tw, double th){
double err = 10;
double maxAngle = PI * 0.25; // 45 degrees, any more would be taller than wide
double angle = maxAngle * 0.5; // start in the middle
double angleDelta = angle * 0.5; // amount to change;
count = 0;
while(count++ < 100){
double rotatedWidth = tw * Math.cos(angle) + th * Math.sin(angle);
err = rotatedWidth - bw;
if(Math.abs(err) < TOLERANCE){
return angle;
} else if(err < 0){
angle -= angleDelta;
} else {
angle += angleDelta;
}
angleDelta *= 0.5;
}
return -1; // found no good angle in 100 attempts
}
Once you have the angle, you can use basic trig to figure out some other points:
Find the lowest y-point of the top edge of the tile where it will be placed. Call this y1
y1 = sin(angle) * tileWidth
Find the lowest point of the left edge of the tile. Call this y2
y2 = sin((PI * 0.5) - radians) * tileHeight
Each added tile will take up y2 vertical space, so the number that will fit is:
(boxHeight - y1) / y2
I created a small ideone.com example that you can play with, also. The code is rather ugly, but it works. For your example in comments(13x8, 14x1), it shows:
Rotated 26.23397827148437 degrees
y1 = 6.188525444904378
y2 = 0.8969959689614577
numTiles = 2
I get a logical riddle and I need an efficient algorithm to solve it.
I have large rectangle (box) with size w*h (width*height).
I have also x other rectangles with not size but with fixed proportions.
What is the fastest way to get the x that will let each of the X rectangle the maximum size to be inside the box(large rectangle)?
Example:
The box rectangle size is 150* 50 (width * height) and i have 25 small rectangles.
The fixed proportion of the small rectangle is 3 (if height =5 then width =5*3=15).
Lets call the height of the rectangle x.
I want to find that largest X that will let me to insert all the rectangle into the big rectangle (into the box).
(The small rectangles will be placed in rows and columns, for example 5 columns and 5 rows by the proportion and maximum height)
Does anyone know an efficient algorithm to solve this?
Um what?
Isn't it just (w*h)/75?
Yeah, brackets aren't needed... but isn't that what you want? Or am i totes missing something here?
Where w and h are the dimensions of the big or parent rectangle.
And 75 is 3*25.
I would attempt to solve this problem empirically (solve using backtracking) instead of analytically, i.e. find all possibilities* (I'll explain the *). Essentially we want to place every rectangle starting with as small as that rect can be to its maximum size (max size can be defined by largest the rectangle can be before bumping into the start point of its neighbors or growing to the container master rect). What this means is if we attempt to place every rect in its every possible size, one of those solutions will be the best solution. Also note that this really a one dimentional problem since the rects height and width is bound by a ratio; setting one implicitly sets the other.
* - When I said all possibilities, I really meant most reasonable possibilities. Since we are in floating point space we cannot test ALL possibilities. We can test for finer and finer precision, but will be unable to test all sizes. Due to this we define a step size to iterate through the size of the rects we will try.
const float STEP_SIZE = 0.0001;
float fLastTotalSize = 0;
int main()
{
PlaceRect(myRects.begin(), myRects.end());
}
void PlaceRect(Iterator currentRect, Iterator end)
{
if (currentRect == end)
{
return;
}
float fRectMaxSize = CalculateMaxPossibleRectSize(*currentRect);
// find the number of steps it will take to iterate from the smallest
// rect size to the largest
int nSteps = fRectMaxSize / STEP_SIZE;
for(int i = 0; i < nSteps; ++i)
{
// based on the step index scale the rect size
float fCurrentRectTestSize = i*STEP_SIZE;
currentRect->SetSize(fCurrentRectTestSize);
float fTotalSize = CalculateTotalSizesOfAllRects();
if (fTotalSize > fLastTotalSize)
{
fLastTotalSize = fTotalSize;
SaveRectConfiguration();
}
// Continue placing the rest of the rects assuming the size
// we just set for the current rect
PlaceRect(currentRect + 1, end);
// Once we return we can now reset the current rect size to
// something else and continue testing possibilities
}
}
Based on the step size and the number of rectangles this may run for a very long time, but will find you the empirical solution.
I am using the diamond-square algorithm to generate random terrain.
It works fine except I get these large cone shapes either sticking out of or into the terrain.
The problem seems to be that every now and then a point gets set either way too high or way too low.
Here is a picture of the problem
And it can be better seen when I set the smoothness really high
And here is my code -
private void CreateHeights()
{
if (cbUseLand.Checked == false)
return;
int
Size = Convert.ToInt32(System.Math.Pow(2, int.Parse(tbDetail.Text)) + 1),
SideLength = Size - 1,
d = 1025 / (Size - 1),
HalfSide;
Heights = new Point3D[Size, Size];
float
r = float.Parse(tbHeight.Text),
Roughness = float.Parse(RoughnessBox.Text);
//seeding all the points
for (int x = 0; x < Size; x++)
for (int y = 0; y < Size; y++)
Heights[x, y] = Make3DPoint(x * d, 740, y * d);
while (SideLength >= 2)
{
HalfSide = SideLength / 2;
for (int x = 0; x < Size - 1; x = x + SideLength)
{
for (int y = 0; y < Size - 1; y = y + SideLength)
{
Heights[x + HalfSide, y + HalfSide].y =
(Heights[x, y].y +
Heights[x + SideLength, y].y +
Heights[x, y + SideLength].y +
Heights[x + SideLength, y + SideLength].y) / 4 - r + ((float)(random.NextDouble() * r) * 2);
}
}
for (int x = 0; x < Size - 1; x = x + SideLength)
{
for (int y = 0; y < Size - 1; y = y + SideLength)
{
if (y != 0)
Heights[x + HalfSide, y].y = (Heights[x, y].y + Heights[x + SideLength, y].y + Heights[x + HalfSide, y + HalfSide].y + Heights[x + HalfSide, y - HalfSide].y) / 4 - r + ((float)(random.NextDouble() * r) * 2);
if (x != 0)
Heights[x, y + HalfSide].y = (Heights[x, y].y + Heights[x, y + SideLength].y + Heights[x + HalfSide, y + HalfSide].y + Heights[x - HalfSide, y + HalfSide].y) / 4 - r + ((float)(random.NextDouble() * r) * 2);
}
}
SideLength = SideLength / 2;
r = r / Roughness;
}
}
Gavin S. P. Miller gave a SIGGRAPH '86 talk about how Fournier, Fussel & Carpenter's original algorithm was fundamentally flawed. So what you're seeing is normal for any naive implementation of the Diamond Square algorithm. You will require a separate approach for smoothing, either post each Diamond-Square compound step, or as a post-process to all diamond-square iterations (or both). Miller addressed this. Weighting and box or gaussian filtering are one option; seeding the initial array to a greater degree than just the initial 4 points (i.e., replicating the resultsets of the first few steps of diamond-square either manually or using some built-in intelligence, but instead supplying unbiased values); the more initial information you give the array before increasing the detail using diamond-square, the better your results will be.
The reason appears to be in how the Square step is performed. In the Diamond step, we've taken the average of the four corners of a square to produce that square's centre. Then, in the subsequent Square step, we take the average of four orthogonally-adjacent neighbours, one of which is the square's centre point we just produced. Can you see the problem? Those original corner height values are contributing too much to the subsequent diamond-square iteration, because they are contributing both through their own influence AND through the midpoint that they created. This causes the spires (extrusive and intrusive), because locally-derived points tend more strongly toward those early points... and because (typically 3) other points do as well, this creates "circular" influences around those points, as you iterate to higher depths using Diamond-Square. So these kinds of "aliasing" issues only appear when the initial state of the array is underspecified; in fact, the artifacting that occurs can be seen as a direct geometric consequence of using only 4 points to start with.
You can do one of the following:
Do local filtering -- generally expensive.
Pre-seed the initial array more thoroughly -- requires some intelligence.
Never smooth too many steps down from a given set of initial points -- which applies even if you do seed the initial array, it's all just a matter of relative depths in conjunction with your own maximum displacement parameters.
I believe the size of the displacement r in each iteration should be proportional to the size of the current rectangle. The logic behind this is that a fractal surface is scale invariant, so the variation in height in any rectangle should be proportional to the size of that rectangle.
In your code, the variation in height is proportional to r, so you should keep it proportional to the size of your current grid size. In other words: multiply r by the roughness before the loop and divide r by 2 in each iteration.
So, instead of
r = r / Roughness;
you should write
r = r / 2;
The actual flaw in the above algorithm is an error in conceptualization and implementation. Diamond square as an algorithm has some artifacting but this is range based artifacts. So the technical max for some pixels is higher than some other pixels. Some pixels are directly given values by the randomness while others acquire their values by the diamond and squared midpoint interpolation processes.
The error here is that you started from zero. And repeatedly added the value to the current value. This causes the range of diamond squared to start at zero and extend upwards. It must actually start at zero and go both up and down depending on the randomness. So the top range thing won't matter. But, if you don't realize this and naively implement everything as added to the value, rather than starting at zero and fluctuating from there, you will expose the hidden artifacts.
Miller's notes were right, but the flaw is generally hidden within the noise. This implementation is shows those problems. That is NOT normal. And can be fixed a few different ways. This was one of the reasons why after I extended this algorithm to remove all the memory restrictions and size restrictions and made it infinite and deterministic1, I then still switched away from the core idea here (the problems extending it to 3d and optimizing for GPUs also played a role.2
Instead of just smoothening with an average, you can use a 2-D median filter to take out extremes. It is simple to implement, and usually generates the desired effect with a lot of noise.