So recursion is not my strong point, and I have been challenged to make a recursive floodFill function that fills a vector of a vector of ints with 1's if the value is zero. My code keeps segfaulting for reasons beyond me. Perhaps my code will make that sound more clear.
This is the grid to be flood filled:
vector<vector<int> > grid_;
It belongs to an object I created called "Grid" that is basically a set of functions to help manipulate the vectors. The grid's values are initialized to all zeros.
This is my flood fill function:
void floodFill(int x, int y, Grid & G)
{
if (G.getValue(x,y))
{
G.setValue(x,y,1);
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x+1,y,G);
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x,y+1,G);
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x-1,y,G);
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x,y-1,G);
}
}
The intention here is to have the function check if a point's value is zero, and if it is, change it to one. Then it should check the one above it for the same. It does this until it either finds a 1 or hits the end of the vector. Then it tries another direction and keeps going until the same conditions as above and so on and so forth until its flood filled.
Can anyone help me fix this? Maybe tell me whats wrong?
Thanks!
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x-1,y,G);
won't work, since you can access index -1 of the underlying vector if x == 0
Same goes for floodFill(x,y-1,G);
This code has a lot of problems. First of all you check with if(G.getValue(x,y)) whether the value at a position is 1, and if so, then you set it to 1 with G.setValue(x,y,1). Think about this for a second, this can't be right. When will you ever set non-zero values to 1?
Then, another more subtle point is that you shouldn't do the recursion into neighbors if they are already set to 1.
As it stands the code you have will likely run until you overflow the stack because just going to recurse forever on the 1's that are connected to wherever you start from.
How about this?
void floodFill(int x, int y, Grid &g) {
if(x >= g.getColumns() || y >= g.getRows()) {
return;
}
floodFill(x+1, y, g);
if( x == 0 ) {
floodFill(x, y+1, g);
}
g.setValue(x, y, 1)
}
I think that will fill the grid without every hitting the same coordinate multiple times, and whenever either index is out of bounds it just returns so no chance of a seg fault.
Related
I'm working on an assignment that gives an integer N and tasks us to find all possible combinations of X, Y such that X + Y = N and Y = X with one digit removed. For example, 302 would have the following solutions:
251 + 51 = 302
275 + 27 = 302
276 + 26 = 302
281 + 21 = 302
301 + 01 = 302
My code to accomplish this can find all of the correct answers, but it runs too slowly for very large numbers (it takes roughly 8 seconds for the largest possible number, 10^9, when I would like for the entire algorithm of up to 100 of these cases to complete in under 3 seconds).
Here's some code describing my current solution:
//Only need to consider cases where x > y.
for(int x = n * 0.5; x <= n; x++)
{
//Only considers cases where y's rightmost digit could align with x.
int y = n - x,
y_rightmost = y % 10;
if(y_rightmost == x % 10 || y_rightmost == (x % 100) / 10)
{
//Determines the number of digits in x and y without division. places[] = {1, 10, 100, 1000, ... 1000000000}
int x_numDigits = 0,
y_numDigits = 0;
while(x >= places[x_numDigits])
{
if(y >= places[x_numDigits])
y_numDigits++;
x_numDigits++;
}
//y must have less digits than x to be a possible solution.
if(y_numDigits < x_numDigits)
{
if(func(x, y))
{
//x and y are a solution.
}
}
}
Where func is a function to determine if x and y only have a one digit difference. Here's my current method for calculating that:
bool func(int x, int y)
{
int diff = 0;
while(y > 0)
{
if(x % 10 != y % 10)
{
//If the rightmost digits do not match, move x to the left once and check again.
x /= 10;
diff++;
if(diff > 1)
return false;
}
else
{
//If they matched, both move to the next digit.
x /= 10;
y /= 10;
}
}
//If the last digit in x is the only difference or x is composed of 0's led by 1 number, then x, y is a solution.
if((x < 10 && diff == 0) || (x % 10 == 0))
return true;
else
return false;
}
This is the fastest solution that I've been able to find so far (other methods I tried included converting X and Y into strings and using a custom subsequence function, along with dividing X into a prefix and suffix without each digit from the right to the left and seeing if any of these summed to Y, but neither worked as quickly). However, it still doesn't scale as well as I need it to with larger numbers, and I'm struggling to think of any other ways to optimize the code or underlying mathematical reasoning. Any advice would be greatly appreciated.
Consider solving a simpler solution first:
Finding X and Y such that X + Y = N
In pseudo-code you steps should look like this:
loop through the array and with every given item do the next:
add this number to Set and check whether there is N - item
This will work as O(n) complexity for unique array.
So improve it to work with duplicated numbers by looping through an array first and adding counter of duplicates for every number. Use some kind of Dictionary for c++ or extend Set. And every time you find the necessary number check for counter.
After doing that you will just have to write this "digit check" function and apply it when finding the value in Set.
I writing a program to numerically find the roots of functions with irrational roots by various methods.
For methods such as linear interpolation, you need to find the approximate range in which a root lies, for this I wrote this code:
bool fxn1 = false;
bool fxn2 = false;
vector<float> root_list;
if(f_x(-100) < 0)
{
fxn2 = true;
}
for(float i = -99.99; i < 100.01; i += 0.01)
{
fxn1 = fxn2;
if(f_x(i) < 0)
{
fxn2 = true;
}
else
{
fxn2 = false;
}
if((fxn1 == false && fxn2 == true) || (fxn1 == true && fxn2 == false))
{
root_list.push_back(i-0.01);
root_list.push_back(i);
}
}
However, for non-continuous functions (i.e. functions with asymptotes), this code will also be triggered when the function swaps from positive to negative values either side of the asymptote.
Is there a way to get the program to tell the difference between a root and an asymptote?
Thanks in advance
If the function, f(x), is converging on a point inside [a,b] then the half-way point (a + b) / 2 should be closer to zero than a or b.
This observation leads to the following procedure:
Let mid = (a + b) / 2
If |f(mid)| < |f(a)| AND |f(mid)| < |f(b)| Then
Algorithm has converged to a root
Else
Algorithm has converged to an asymptote
End
In this pseudo code |.| denotes floating-point absolute value.
Finding numerically a root only make sense if the function has nice properties, and at least is continuous. What would you think about this one:
f: x -> f(x) defined by:
2 * i < x < 2 * i + 1 (i element of Z) : f(x) = x
2 - i + 1 < x < 2 * i (i element of Z) : f(x) = -x
x = i (i element of Z) : f(x) = 1
It is perfectly defined on R, is bounded on any bounded interval, has positive and negative values on any interval of size > 1, and is continuous on any non integer point, but it has no root.
It is simply because the rule that a root must exist on segment ]x, y[ if x < 0 < y or y < 0 < x only applies if the function is continuous on the interval.
And good luck if you want to numerically test for continuity of a function...
I have this assigment in university where I'm given the code of a C++ game involving pathfinding. The pathfinding is made using a wave function and the assigment requires me to make a certain change to the way pathfinding works.
The assigment requires the pathfinding to always choose the path farthest away from any object other than clear space. Like shown here:
And here's the result I've gotten so far:
Below I've posted the part of the Update function concerning pathfinding as I'm pretty sure that's where I'll have to make a change.
for (int y = 0, o = 0; y < LEVEL_HEIGHT; y++) {
for (int x = 0; x < LEVEL_WIDTH; x++, o++) {
int nCost = !bricks[o].type;
if (nCost) {
for (int j = 0; j < 4; j++)
{
int dx = s_directions[j][0], dy = s_directions[j][1];
if ((y == 0 && dy < 0)
|| (y == LEVEL_HEIGHT - 1 && dy > 0)
|| (x == 0 && dx < 0)
|| (x == LEVEL_WIDTH - 1 && dx > 0)
|| bricks[o + dy * LEVEL_WIDTH + dx].type)
{
nCost = 2;
break;
}
}
}
pfWayCost[o] = (float)nCost;
}
}
Also here is the Wave function if needed for further clarity on the problem.
I'd be very grateful for any ideas on how to proceed, since I've been struggling with this for quite some time now.
Your problem can be reduced to a problem known as minimum-bottle-neck-spanning-tree.
For the reduction do the following:
calculate the costs for every point/cell in space as the minimal distance to an object.
make a graph were edges correspond to the points in the space and the weights of the edges are the costs calculated in the prior step. The vertices of the graph corresponds to the boundaries between cell.
For one dimensional space with 4 cells with costs 10, 20, 3, 5:
|10|20|3|5|
the graph would look like:
A--(w=10)--B--(w=20)--C--(w=3)--D--(w=5)--E
With nodes A-E corresponding to the boundaries of the cells.
run for example the Prim's algorithm to find the MST. You are looking for the direct way from the entry point (in the example above A) to the exit point (E) in the resulting tree.
Is this micro-optimization, or is it optimization at all?
void Renderer::SetCamera(FLOAT x, FLOAT y, FLOAT z) {
// Checking for zero before doing addition?
if (x != 0) camX += x;
if (y != 0) camY += y;
if (z != 0) camZ += z;
// Checking if any of the three variables are not zero, and performing the code below.
if (x != 0 | y != 0 | z != 0) {
D3DXMatrixTranslation(&w, camX, camY, camZ);
}
}
Would running a for.. loop with the condition having vector.size() force the application to recount the elements in the vector on each loop?
std::vector<UINT> vect;
INT vectorSize = vect.size();
for (INT Index = 0; Index < vectorSize; Index++) {
// Do vector processing
}
// versus:
std::vector<UINT> vect;
for (INT Index = 0; Index < vect.size(); Index++) {
// Do vector processing
}
I'm using Visual Studio and as for the second question, it seems like something a compiler could optimize, but I'm just not sure on that.
Depending on the implementation of vector, the compiler may or may not understand that size is not changed. After all, you call different vector functions inside the loop, any of which might change size.
Since vector is a template, then the compiler knows everything about it, so if it works really hard, it could understand that size doesn't change, but that's probably too much work.
Often, you would want to write like this:
for (size_t i = 0, size = vect.size(); i < size; ++i)
...
While we're at it, a similar approach is used with iterators:
for (list<int>::iterator i = lst.begin(), end = lst.end(); i != end; ++i)
...
Edit: I missed the first part:
Is this optimization?
if (x != 0) camX += x;
if (y != 0) camY += y;
if (z != 0) camZ += z;
No. First of all, even if they were int, it wouldn't be optimization since checking and branching when the values are probably most of the times not zero is more work.
Second and more importantly, they are float. This means that besides the fact that you shouldn't directly compare them to 0, they are basically almost never exactly equal to 0. So the ifs are 99.9999% true.
Same thing applies to this:
if (x != 0 | y != 0 | z != 0)
In this case however, since matrix translation could be costly, you could do:
#define EPS 1e-6 /* epsilon */
if (x > EPS || x < -EPS || y > EPS || y < -EPS || z > EPS || z < -EPS)
and now yes, comparing to a matrix multiplication, this is probably an optimization.
Note also that I used || which gets short-circuited if for example right from the beginning x > EPS is true (it won't calculate the rest), but with | that won't happen.
I suspect that on many architectures the first three lines are an anti-optimization because they may introduce a floating point compare and then branch which can be slower than just always doing the addition (even if it's floating point).
On the other hand making sure that at least one component is non-zero before doing the transformation seems sound.
For your second case, size has to be constant time and will almost certainly be inlined out to a direct access to the vector's size. It's most likely fully optimizable. That said, sometimes it can make the code/loop easier to read by saving the size off because that clearly shows you are asserting the size won't change during the loop.
Firstly, Regarding the vector.size(), see
this SO question. On a side note, I haven't seen an implementation where std::vector::size() isn't O(1).
if (x != 0) camX += x; this cmp and consequent jne however is going to be slower than simply adding the variable x no matter what. Edit: Unless you expect well over 50 % cache misses on camX
The first one is probably a pessimisation, the check for 0 is probably slower than the addition. On top of that, in the check before the call to D3DXMatrixTranslation, you use | instead of the short-circuiting logical or ||. Since the check before the function call is probably a time-saver (or even semantically necessary), wrap the entire code in that check,
void Renderer::SetCamera(FLOAT x, FLOAT y, FLOAT z) {
if (x != 0 || y != 0 || z != 0) {
camX += x;
camY += y;
camZ += z;
D3DXMatrixTranslation(&w, camX, camY, camZ);
}
}
if all of x, y and z are zero, nothing need be done, otherwise, do all.
For the second, the compiler can hoist the vector.size() outside the loop if it can determine that the size doesn't change while the loop runs. If the compiler cannot determine that, it must not hoist the size() computation outside the loop.
Doing that yourself when you know that the size doesn't change is good practice.
Can someone tell me whether my rectangle intersect code is correct?
bool checkCollide(int x, int y, int oWidth, int oHeight,
int x2, int y2, int o2Width, int o2Height) {
bool collide = false;
if (x >= x2 && x <= x2+o2Width && y >= y2 && y <= y2+o2Height)
collide = true;
if (x+oWidth >= x2 && x+oWidth <= x2+o2Width && y >= y2 && y <= y2+o2Height)
collide = true;
if (x >= x2 && x<= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height)
collide = true;
if (x+oWidth >= x2 && x+oWidth <= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height)
collide = true;
return collide;
}
Nope, a corner of a rectangle doesn't have to be in the other rectangle for the rectangles to collide. What you want to do is to find the logic when they do not intersect and use the negation of that. The picture below shows two rectangles that clearly intersect each other, but only the sides are intersecting, not the corners.
Just formulate the logic as follows: What does it take for the blue to not intersect the red? Well it's either completely to the right, completely to the left, up or below. Formulate an if statement to that and negate it.
Let me help you with the beginning:
if (!(x2 > x+oWidth || x2+o2Width < x || ..))
collide = true;
Following on from Magnus's answer, I'd take a slightly different approach.
As he says, if the two don't intersect then one will be completely left, completely right, etc. For performance however you can stop testing as soon as any of these conditions are found to be false, e.g.:
if (x2 + owidth2 < x)
return false; // box 2 is left of box 1
if (x + owidth < x2)
return false; // box 1 is left of box 2
// etc...
First implement interval intersection (i.e. one dimension).
Then you can implement rectangle intersection by first applying interval intersection to the x-coordinates and then applying interval intersection to the y-coordinates.
checkCollide(0, 0, 3, 3, 1, 1, 1, 1) == false
I'm guessing that's not what you want.