determine box size needed - math

I am trying to calculate the size a big rectangle needed to pack smaller ones.he smaller rectangle have fixed know size and the big rectangle have a fixed width.
In the image, 6 rectangle can fit the big rectangle in which the initial w and height h1 . Now if give more small rectangle, how do i determine the height h2, h3, h4.
i initially went the bin packing route, but this didnt really help as it mainly focused on how many smaller rectangle can fit a big one, but i need instead how much size (height) is needed to fit a certain quantity of smaller boxes.
How do i find the heights h2, h3, and h4.
w = width of original rectangle
h1 = height of original rectangle
w and h1 is given say 300, 400
bh = small rectangles height
bw = small rectangles width
bh and bw is the same for all the rectangles and is given say 40, 40
sb = number of small boxes
three different sets are provided in this example, for each set the required height of the box needed to hold the small rectangles needs to be calculated
for the first set which has sb as 6, I need to find h2
for the second set which has sb as 7, I need to find h4
for the third set which has sb as 8, I need to find h3

It`s still a bit unclear to me. But here is a try to answer your question.
The number of boxes that fit in a single row is:
boxesInRow = floor(w / bw)
In order to fit n boxes, you need the following count of rows:
rows = ceil(n / boxesInRow)
And the height of this big box is then just:
height = rows * bh
Now comes the part where I am not sure. You say that sb is the number of boxes. However, for the first image (h2), you say that sb should be 6, but I count 9 boxes. So apparently, you ignore the first row. If this is really the case, the final formula is:
height = bh * (rows + 1)
= bh * (ceil(sb / floor(w / bw)) + 1)

Related

How to subdivide the space inside a small multiple

I need to create small multiples (like the one shown in the picture) using ggplot2 where each circle occupies 70% of the total size of it's own small multiple and the remaining 30% is empty space.
I know the center and the radius of the circle.
Question: Is it possible to do this, and if so, how?
Area of ​​a circle = C = π * r²
Area of your square = S = width * length = side²
So just calculate C, so you can calculate how big S must be to fullfill your criteria. When you know S you know the side, which translates to how you have to set the axis limits for x and y.

filling parent container with changing number of child video elements, each with aspect ratio

I have a resizable parent element containing an ever-changing number of video elements. Each video should maintain a width/height aspect ratio of 4/3. As the total size of the parent is stretched and changed, each video element should resize itself so as to maximize the total area of video space, or to minimize the unused (non-video) area within the parent.
I feel like this should be relatively easy yet here I am hours later... what am I forgetting from childhood geometry?
There are no constraints on css elements I can use - I've tried with grids and flexbox layouts, all to little-to-no avail.
Your task is to place n rectangles with fixed C=W/H = 4/3 ratio on the rectangular container with given Width and Height
Let scaled rectangle height is h (unknown yet), width is w = C * h
Every row of grid contains nr small rectangles
nr = Floor(Width / (C * h)) // rounding down
Every column contains nc rows
nc = Floor(Height / h)
Write inequality
n <= nc * nr
n <= Floor(Width / (C * h)) * Floor(Height / h)
and solve it for unknown h (find maximal possible h value)
For real values of parameters h might be found getting initial approximate value:
h0 = Ceil(Sqrt(Width * Height / (n * C))) //rounding up
and decrementing h value until inequality becomes true

How to compare two Ratios of Rectangles / Sizes to determine their percentages of differences?

I have a ractangle whose ratio is 80:40 and other rectangles with similar aspect ratios within a humbral for example 80:35, 85:45, that unbral is a decimal or integer.
My problem is that I need to compare other rectangles with the first one and determine a difference in their respective aspect ratios in percentages, for example: 80:30 is 20% different in aspect ratio than 80:40.
(20% is not a calculated data, it is an example idea, because I don't know how to do it).
Could it be that a totally opposite aspect ratio is 100% different? For example: 80:40 is 100% different than 40:80
Imagine that you have a collection of rectangles and a target rectangle and you have to filter the collection leaving only those rectangles that have an aspect ratio similar to the target rectangle.
Sample:
private float GetDiffRatio(FloatSize size1, FloatSize size2) {
float fixedR1 = size1.Width / size1.Height;
if (fixedR1 >= 0)
// Invert and negative.
fixedR1 = -(size1.Height / size1.Width);
float fixedR2 = size2.Width / size2.Height;
if (fixedR2 >= 0)
// Invert and negative.
fixedR2 = -(size2.Height / size1.Width);
float rDiff = fixedR1 - fixedR2;
return rDiff * 100f;
}
Test:
float diffRatio = GetDiffRatio(new FloatSize(100f, 50f), new FloatSize(50f, 100f));
Results = -100f
Test2 (inverted order of parameters):
float diffRatio = GetDiffRatio(new FloatSize(50f, 100f), new FloatSize(100f, 50f));
Results = 100f
I am not sure that this is a valid or correct form, I do not know if it can generate any condition that returns a wrong percentage of similarity.
The answer to this question depends a lot on what exactly you're trying to do or you're planning to uses this similarity function for. I find it very unintuitive to say that opposite aspect ratio leads to 0% similarity. I think comparing two rectangles r1=(2.1,2) and r2=(2,2.1) should be a lot more similar to each other then for example r3=(1,5) r4=(5,1).
This is not me saying that it couldn't be useful in some case to have a similarity function like your's, I just want to explain that it depends a lot on what you're doing ...
I would say a very obvious solution would be to just divide width by height of every rectangle and take as similarity-function s1 the absolute value from both values subtracted. So for my provided examples the result would be:
s1(r1,r2) = | 2.1/2 - 2/2.1 | = 0.0976...
s1(r2,r3) = | 1/5 - 5/1 | = 4.8
If it is also important that you have values between 0 and 1 you could additionally plug this values in for example this function ...
where
b must be smaller than 0 and is a parameter with what you can controll how fast the funciton converges to 1. YOu can play around with it here: https://www.desmos.com/calculator/nwlq3ujouq
In the case you really want something as you suggested, i would simply do the following:
You take your constraint that every rectangle is between the ratio a:b and c:d. Than you calculate x1=a/b and x2=c/d and then you interpolate the value from zero to one between those values so:
h(x1) = 0
h(x2) = 1
if you need more details on how to do this look here https://en.wikipedia.org/wiki/Linear_interpolation but i think it's very straight forward.
The similarity function s3 can then be build again with the absolute value of the difference
s3=| h(r1)-h(r2) |

Filling a grid with boxes with numbers with decreasing size

There is this interesting game, that has numbers in a grid, where each number has progressively smaller font. The player's task is to click on the numbers in succession.
I'm interested in the algorithm that creates the boxes for the numbers, I cannot think of a way it works.
Apparently the grid has N numbers (apart from the 1.88 in the picture), number 1 has the biggest font and succesively the font size decreases. Then the numbers are somehow placed on the grid and boxes grow around them. But it doesn't seem totally random, as there are some horizotal lines that go across the whole grid.
Do you have an idea on how this might work?
It looks to me as though the boxes have been generated by successive division. That is, starting with the full rectangle, a dividing line (horizontal or vertical) was placed, and then the two resulting rectangles were subdivided in turn, until there were enough rectangles for the game.
Here's a sketch of the first algorithm I would try. N is the number of rectangles I want to divide the original rectangle into, and A is a critical aspect ratio used to stop the small rectangles getting too narrow. (Perhaps A = 1.5 would be a good start.)
Create an empty priority queue and add the full rectangle to it.
If the length of the priority queue is greater than or equal to N, stop.
Remove the largest rectangle, R, from the priority queue.
Choose whether to divide it horizontally or vertically: if its aspect ratio (width/height) is greater than A, divide it vertically; if less than 1/A, divide it horizontally, otherwise choose at random.
Decide where to put the dividing line. (Perhaps randomly between 40% and 60% along the chosen dimension.)
This divides R into two smaller rectangles. Add both of them to the priority queue. Go to step 2.
When this algorithm completes, there are N rectangles in the queue. Put the number 1 in the largest of them, the number 2 in the second largest, and so on.
It turns out that putting the numbers into the boxes is not quite as straightforward as I assumed in my first attempt. The area metric works well for subdividing the rectangles nicely, but it doesn't work for putting the numbers into the boxes, because for fitting text into a box, the height and width both have to be taken into account (the area is not so useful).
Instead of explaining the algorithm for putting numbers into the boxes, I will just give you some sample code in Python and let you reverse-engineer it!
import heapq, itertools, random
import Image, ImageDraw, ImageFont
# ALGORITHM PARAMETERS
aspect_max = 1.5 # Above this ratio, always divide vertically
aspect_min = 1.0 # Below this ratio, always divide horizontally
div_min = 0.4 # Minimum position for dividing line
div_max = 0.6 # Maximum position for dividing line
digit_ratio = 0.7 # Aspect ratio of widest digit in font
label_margin = 2 # Margin around label (pixels)
class Rectangle(object):
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
self.area = self.w * self.h
self.aspect = float(self.w) / self.h
def __le__(self, other):
# The sense of this comparison is inverted so we can put
# Rectangles into a min-heap and be able to pop the largest.
return other.area <= self.area
def __repr__(self):
return 'Rectangle({0.x}, {0.y}, {0.w}, {0.h})'.format(self)
def divide(self, n):
"""
Divide this rectangle into `n` smaller rectangles and yield
them in order by area (largest first).
"""
def division(l):
return random.randrange(int(l * div_min), int(l * div_max))
queue = [self]
while len(queue) < n:
r = heapq.heappop(queue)
if (r.aspect > aspect_max
or r.aspect > aspect_min
and random.random() < 0.5):
# Vertical division
w = division(r.w)
heapq.heappush(queue, Rectangle(r.x, r.y, w, r.h))
heapq.heappush(queue, Rectangle(r.x + w, r.y, r.w - w, r.h))
else:
# Horizontal division
h = division(r.h)
heapq.heappush(queue, Rectangle(r.x, r.y, r.w, h))
heapq.heappush(queue, Rectangle(r.x, r.y + h, r.w, r.h - h))
while queue:
yield heapq.heappop(queue)
def font_height(self, n):
"""
Return the largest font height such that we can draw `n`
digits in this rectangle.
"""
return min(int((self.w - label_margin * 2) / (digit_ratio * n)),
self.h - label_margin * 2)
def draw_rectangles(rectangles, fontfile):
"""
Create and return an Image containing `rectangles`. Label each
rectangle with a number using the TrueType font in `fontfile`.
"""
rectangles = list(rectangles)
im = Image.new('RGBA', (1 + max(r.x + r.w for r in rectangles),
1 + max(r.y + r.h for r in rectangles)))
draw = ImageDraw.Draw(im)
for digits in itertools.count(1):
rectangles = sorted(rectangles,
key = lambda r: r.font_height(digits),
reverse = True)
i_min = 10 ** (digits - 1)
i_max = 10 ** digits
i_range = i_max - i_min
for i in xrange(i_range):
if i >= len(rectangles): return im
r = rectangles[i]
draw.line((r.x, r.y, r.x + r.w, r.y, r.x + r.w, r.y + r.h,
r.x, r.y + r.h, r.x, r.y),
fill = 'black', width = 1)
label = str(i + i_min)
font = ImageFont.truetype(fontfile, r.font_height(digits))
lw, lh = font.getsize(label)
draw.text((r.x + (r.w - lw) // 2, r.y + (r.h - lh) // 2),
label, fill = 'black', font = font)
rectangles = rectangles[i_range:]
Here's a sample run:
>>> R = Rectangle(0, 0, 400, 400)
>>> draw_rectangles(R.divide(30), '/Library/Fonts/Verdana.ttf').save('q10009528.png')
The pattern of the cuts looks recursive. That is, the process of dividing the region into rectangles consists of cutting a rectangle in two, over and over. There are two cuts that divide the whole rectangular region (the horizontal cuts above and below 1), so we can't tell which cut came first, but we see the cuts as a kind of tree: the cut that separates 1 from 10 produced a large rectangle below it (20, 21, 4, 10, etc.), which was then divided by the vertical cut between 21 and 4, the rectangle containing 4 was later divided by the cut that separates 4 and 14, and so on. There are N cuts that produce N regions plus one leftover ("1.88") which is not necessary but which might give us a clue.
Now we just have to figure out the order of the cuts, the choice of proportion and the choice of orientation.
Consecutive numbers are rarely neighbors, so it looks as if numbers are not assigned as the cutting progresses. Instead, the region is chopped into rectangles, the rectangles are sorted by size and then numbers are assigned (notice that 20 and 21 are neighbors, but they were formed by other cuts after the one that divides them).
A plausible hypothesis for the order of the cuts is that the algorithm always cuts the largest rectangle. If that were not true, we might see, e.g., 14 bigger than 15 and 18 combined, and I see no example of that.
Proportion... With careful measurement we could see the actual distribution of proportions, but I don't feel like doing that much work. We see no very long, thin rectangles and no 50/50 cuts, so at a guess I'd say the algorithm chooses randomly, in some range like [0.6, 0.8]. Maybe it tries to avoid making a rectangle very close to the size of a rectangle that already exists. After all the cuts, the rectangle chosen to be left over ("1.88") is neither the biggest nor the smallest; maybe it's random, maybe it's the second-biggest, maybe it's something else-- more examples would be useful.
The orientation seems to be strongly biased towards cutting rectangles across their narrow width, rather than "lengthwise". This has the effect of producing rectangles more like squares and less like books on a shelf. The only possible exception I can see is the 1-9 cut, which might divide the block whose lower-right number is 1 lengthwise. But that depends on the order of cuts above and below 1, so it leads to a hypothesis: the algorithm always cuts a rectangle along its shorter dimension, and the 1-9 cut was actually the first.
That's about as far as I can go, short of breaking out a ruler and calculator.

Scaling ratio of two different resolutions

I have two different resolutions, the original one is 567x756 (wXh), the one which I want to display is 768x1024 (wXh). How to find out the scaling ratio for these two resolutions? For example if the font size used in 567x756 resolution is 7 pts then what's the values I should multiply with the font size (7 pts) to display the text in 768x1024 resolution.
Whenever you hear "scaling", think "proportions":
You can set up a proportion, here:
old width new width
--------- = --------
old font new font
567 768
---- = -----
7 x
567*x = 5376
x = 9.48
So your new font is about 9.48, or 9 if you only want integers.
Alternatively, you could also use the height-to-height proportion in your calculations instead of width-to-width. Or use the average font height you'd get from doing either. Or do old_area/old_font^2 = new_area/new_font^2
If you want a way to find the scaling factor for any arbitrary new width:
old width new width
--------- = --------
old font new font
567 w
---- = ---
7 x
567*x = 7*w
x = (7/567) * w
Given your new w (or h, or w/e), the new font size is (7/567) * w
The aspect ratios are the same for both resolutions, so just take one dimension and use that as your scaling ratio, i.e.
1024/756
Which is about 1.35. Or if you want to scale in the other direction, 0.738

Resources