Can anyone suggest any links, ideas or algorithms to generate flowers randomly like the one as my profile pic? The profile pic flower has only a 10 x 10 grid and the algorithm is not truly random. I would also prefer that the new algorithm use a grid of about 500 x 500 or even better, allow the user to pick the size of the grid.
[Plant[][] is declared as int plant[10][10];]
public void generateSimpleSky(){
for(int w2=0;w2<10;w2++)
for(int w3=0;w3<10;w3++)
plant[w2][w3]=5;
}
public void generateSimpleSoil(){
for(int q=0;q<10;q++)
plant[q][9]=1;
}
public void generateSimpleStem(){
int ry=rand.nextInt(4);
plant[3+ry][8]=4;
xr=3+ry;
for(int u=7;u>1;u--){
int yu=rand.nextInt(3);
plant[xr-1+yu][u]=4;
xr=xr-1+yu;
}
}
public void generateSimpleFlower(){
plant[xr][2]=3;
for(int q2=1;q2<4;q2++)
if((2-q2)!=0)
plant[xr][q2]=2;
for(int q3=xr-1;q3<=xr+1;q3++)
if((xr-q3)!=0)
plant[q3][2]=2;
}
It sounds like a reasonably simple problem where you just generate 1 parameter at a time, possibly based on the output of the previous variables.
My model of a flower will be: It has just a reasonably upright stem, a perfectly round center, some amount of leaves on the stem on alternating sides, petals perfectly distributed around the center.
random() is just a random number within some chosen bounds, the bounds may be unique for each variable. random(x1, x2, ..., xn) generates a random number within some bounds dependent on the variables x1, x2, ..., xn (as in stemWidth < stemHeight/2, a reasonable assumption).
The Stem
stemXPosition = width / 2
stemHeight = random()
stemWidth = random(stemHeight)
stemColour = randomColour()
stemWidthVariationMax = random(stemWidth, stemHeight)
stemWidthVariationPerPixel = random(stemWidth, stemHeight)
stemWidthVariationMax/-PerPixel are for generating a stem that isn't perfectly straight (if you want to do something that complicated, a low PerPixel is for smoothness). Generate the stem using these as follows:
pixelRelative[y-position][0] := left x-position at that y-position relative to the stem
pixelRelative[y-position][1] := right x-position at that y-position relative to the stem
pixelRelative[0][0] = randomInRange(-stemWidthVariationMax, stemWidthVariationMax)
for each y > 0:
pixelRelative[y-1][0] = max(min(randomInRange(pixel[y] - stemWidthVariationPerPixel,
pixel[y] + stemWidthVariationPerPixel),
-stemWidthVariationMax),
stemWidthVariationMax)
//pixelRelative[0][1] and pixelRelative[y-1][1] generated same as pixelRelative[y-1][i]
for each y:
pixelAbsolute[y][0] = width / 2 - stemWidth / 2 + pixelRelative[y][0]
pixelAbsolute[y][1] = width / 2 + stemWidth / 2 + pixelRelative[y][1]
You can also use arcs to simplify things and go more than 1 pixel at a time.
The Top
centerRadius = random(stemHeight)
petalCount = random() // probably >= 3
petalSize = random(centerRadius, petalCount)
It's not too easy to generate the petals, you need to step from 0 to 2*PI with step-size of 2*PI/petalCount and generate arcs around the circle. It requires either a good graphics API or some decent maths.
Here's some nicely generated tops of flowers, though seemingly not open-source. Note that they don't have a center at all. (or centerRadius = 0)
The Leaves
You could probably write an entire paper on this, (like this one) but a simple idea would just be to generate a 1/2 circle and extend lines outward from there to meet at 2*the radius of the circle and to draw parallel lines on the flower.
Once you have a leaf generation algorithm:
leafSize = random(stemHeight) // either all leaves are the same size or generate the size for each randomly
leafStemLength = random(leafSize) // either all leaves have the same stem length or generate for each randomly
leafStemWidth = random(leafStemLength)
leaf[0].YPosition = random(stemHeight)
leaf[0].XSide = randomly either left or right
leaf[0].rotation = random between say 0 and 80 degrees
for each leaf i:
leaf[i].YPosition = random(stemHeight, leaf[i-1]) // only generate new leaves above previous leaves
leaf[i].XSide = opposite of leaf[i].XSide
Last words
The way to determine the bounds of each random would be either to argue it out, or give it some fixed value, generate everything else randomly a few times, keep increasing / decreasing it until it starts to look weird.
10 x 10 versus 500 x 500 would probably require greatly different algorithms, I wouldn't recommend the above for below 100 x 100, maybe generate a bigger image and simply shrink it using averaging or something.
Code
I started writing some Java code, when I realised it may take a bit longer than I would like to spend on this, so I'll show you what I have so far.
// some other code, including these functions to generate random numbers:
float nextFloat(float rangeStart, float rangeEnd);
int nextInt(int rangeStart, int rangeEnd);
...
// generates a color somewhere between green and brown
Color stemColor = Color.getHSBColor(nextFloat(0.1, 0.2), nextFloat(0.5, 1), nextFloat(0.2, 0.8));
int stemHeight = nextInt(height/2, 3*height/4);
int stemWidth = nextInt(height/20, height/20 + height/5);
Color flowerColor = ??? // I just couldn't use the same method as above to generate bright colors, but I'm sure it's not too difficult
int flowerRadius = nextInt(Math.min(stemHeight, height - stemHeight)/4, 3*Math.min(stemHeight, height - stemHeight)/4);
Related
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.
Sorry about the vague title. I'm not sure how to concisely word what I'm about to ask. This is more of a math/algorithms question than a programming question.
In an app that I'm developing, we have a value that can fluctuate anywhere between 0 and a predetermined maximum (in testing it's usually hovered around 100, so let's just say 100). This range of data is continuous, meaning there are an infinite number of possible values- as long as it's between 0 and 100, it's possible.
Right now, any value returned from this is mapped to a different range that is also continuous- from 1000 to 200. So if the value from the first set is 100, I map it to 200, and if the value from the first set is 0, it gets mapped to 1000. And of course everything in between. This is what the code looks like:
-(float)mapToRange:(float)val withMax:(float)maxVal{
// Establish range constants.
const int upperBound = 1000;
const int lowerBound = 200;
const int bandwidth = upperBound - lowerBound;
// Make sure we don't go above the calibrated maximum.
if(val > maxVal)
val = maxVal;
// Scale the original value to our new boundaries.
float scaled = val/maxVal;
float ret = upperBound - scaled*bandwidth;
return ret;
}
Now, what I want to do is make it so that the higher original values (closer to 100) increase in larger increments than the lower original values (closer to 0). Meaning if I slowly start decreasing from 100 to 0 at a steady rate, the new values starting at 200 move quickly toward 1000 at first but go in smaller increments the closer they get to 1000. What would be the best way to go about doing this?
Your value scaled is basically the 0-100 value represented in the range 0-1 so it's good to work with. Try raising this to an integer power, and the result will increase faster near 1 and slower near 0. The higher the power, the larger the effect. So something like:
float scaled = val/maxVal;
float bent = scaled*scaled*scaled*scaled; // or however you want to write x^4
float ret = upperBound - bent*bandwidth;
Here's a sketch of the idea:
That is, the span A to B, maps to the smaller span a to b, while the span C to D maps to the larger span c to d. The larger the power of the polynomial, the more the curve will be bent into the lower right corner.
The advantage of using the 0 to 1 range is that the endpoints stay fixed since x^n=x when x is 0 or 1, but this, of course, isn't necessary as anything could be compensated for by the appropriate shifting and scaling.
Note also that this map isn't symmetric (though my drawing sort of looks that way), though course a symmetric curve could be chosen. If you want to curve to bend the other way, choose a power less than 1.
I'm coding a game using Box2D and SFML, and I'd like to let my users import their own textures to use as physics polygons. The polygons are created using the images' alpha layer. It doesn't need to be pixel perfect, and this is where my problem is. If it's pixel-perfect, it's going to be way too buggy when the player gets stuck between two rather complex shapes. I have a working edge-detection algorithm, and it produces something like this. It's pixel per pixel (and the shape it's tracing is simply a square with an dip). After that, I have a simplifying algorithm that produces this. It works fine to me, but if every single corner is traced like that, I'm going to have some problems. The code for the vector-simplifying is this:
//borders is a std::vector containing simple Box2D b2Vec2 (2D vector class containing an x and a y)
//vector shortener
for(unsigned int i = 0; i < borders.size(); i++)
{
int x = 0, y = 0;
int counter = 0;
//get the values for x and y that need to be added to check whether in a line or not
x = borders[i].x - borders[i-1].x;
y = borders[i].y - borders[i-1].y;
//while points are aligned..
while((borders[i].x + x*counter == borders[i + counter].x) && (borders[i].y + y*counter == borders[i+counter].y))
{
counter++;
}
if(counter-1 > i)
{
borders.erase(borders.begin() + i, borders.begin() + i + counter -1);
}
}
So my question is, how can I transform the previous set of vectors into something a bit less precise? Are there any rounding algorithms out there? If so, which is best? Any tips you can give me? It doesn't matter whether the resulting polygon is convex or concave, I'm triangulating it anyways.
Thanks,
AsterAlff
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.
Probably an easy question, but I could not find an easy solution so far. I'm working on a simple image recognition software for a very specific use case.
Given is a bunch of points that are supposedly on a straight line. However, some of the points are mistakenly placed and away from the line. Especially near the ends of the line, points may happen to be more or less inaccurate.
Example:
X // this guy is off
X // this one even more
X // looks fine
X
X
X // a mistake in the middle
X
X // another mistake, not as bad as the previous
X
X
X
X
X // we're off the line again
The general direction of the line is known, in this case, it's vertical. The actual line in the example is in fact vertical with slight diagonal slope.
I'm only interested in the infinite line (that is, it's slope and offset), the position of the endpoints is not important.
As additional information (not sure if it is important), it is impossible for 2 points to lie next to each other horizontally. Example:
X
X
X
X X // cannot happen
X
X
Performance is not important. I'm working in C#, but I'm fine with any language or just a generic idea, too.
I think you're looking for Least squares fit via Linear Regression
Linear regression (as mentioned by others) is good if you know you do not have outliers.
If you do have outliers, then one of my favorite methods is the median median line method:
http://education.uncc.edu/droyster/courses/spring00/maed3103/Median-Median_Line.htm
Basically you sort the points by the X values and then split the points up into three equal sized groups (smallest values, medium values, and largest values). The final slope is the slope of the line going through the median of the small group and through the median of the large group. The median of the middle group is used with the other medians to calculate the final offset/intercept.
This is a simple algorithm that can be found on several graphing calculators.
By taking the three medians, you are completely ignoring any outliers (either on the far left, far right, far up, or far down).
The image below shows the linear regression and median-median lines for a set of data with a couple of large outliers.
Mike is spot on! Use the following:
double[] xVals = {...};
double[] yVals = {...};
double xMean = 0;
double yMean = 0;
double Sxy = 0;
double Sxx = 0;
double beta0, beta1;
int i;
for (i = 0; i < xVals.Length; i++)
{
xMean += xVals[i]/xVals.Length;
yMean += yVals[i]/yVals.Length;
}
for (i = 0; i < xVals.Length; i++)
{
Sxy += (xVals[i]-xMean)*(yVals[i]-yMean);
Sxx += (xVals[i]-xMean)*(xVals[i]-xMean);
}
beta1 = Sxy/Sxx;
beta0 = yMean-beta1*xMean;
Use beta1 as the slope and beta0 as the y-intercept!