filling an area of a matrix with characters - c++

I have created a matrix using 2D vectors. The code I used is
int RC=50;
vector<vector<int> > matrix;
vector<int>row;
///////////Building Grid//////////////////
for(int i=0;i<RC;i++)
{
for(int j=0;j<RC;j++)
{
row.push_back(0);
}
matrix.push_back(row);
}
//////////Printing Grid///////////////////
for(int i=0;i<RC;i++)
{
for(int j=0;j<RC;j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
The output of the above code is
Now what I want is to fill a block of size 6x6 inside the matrix with '$' or any character by inputting the bottom left location of the block. For example if i gave the location as (10,4), then I would like to place a block of '$' (size 6x6) whose bottom left co-ordinates are (10,4).
EDIT-1
I added the code
int si=3;
int sy=3;
for(int i=0;i<RC;i++)
{
for(int j=0;j<RC;j++)
{
if(i>=si && i<=si+6 && j>=sy && j<=sy+6)
{
matrix[i][j]=1;
}
else
{
matrix[i][j]=0;
}
}
}
and I got the output as
I am reading the co-ordinates as the top left ones, what should I do to read the co-ordinates as the bottom left ones and build the block from there?

You need to tackle the problem logically and break down the steps you need to solve it. You're staring at a big block of zeros and that isn't going to help. So, walk through it with pseudo code and a handy, dandy piece of paper and pencil.
Ask smaller questions about the larger problem at hand. How do you go from bottom left coordinate to the coordinate you wish to start with? How do you determine when to stop? Do I understand what I just did? If not why don't I understand it?
Baby step by baby step while you're learning. Take the time to understand why something either worked the way you wanted it to or failed to work. Do this and you'll be a much better coder for it.

Related

furthest right black pixel

I have a black and white image, and I'm only interested in finding the x-position of the furthest right black pixel, but I'm not sure how to proceed. Any help would be appreciated. Oh, and I'm using CImg and VC2008.
Alright, I feel pretty dumb since I didn't realize for loops could be iterated backwards. Anyways, here is what I have now.
int right_edge(CImg<unsigned char> bw)
{
int width = bw.width();
int height = bw.height();
for( int i=height; i>0; i-- ){
for( int j=width; j>0; j-- ){
if( bw[j,i] == (0,0,0) ) //I know this line is the problem
cout << j << endl;
return 0;
}
}
}
The code compiles, but doesn't output as expected. I know the line with the if statement is formatted wrong. I've tried a whole bunch of Google results, but nothing has seemed to work (ie I'm probably messing up)
Simple psuedocode algorithm:
for each column of pixels (starting from the rightmost column, moving left)
for each row
if this pixel is black
return x coordinate of column
I am deliberately leaving specifics out, as this seems to be a homework question and no effort has been shown on your part. But, this should be enough to get you started.

C++ 2D Vector setting a position within the vector

I have an assignment to make a robot controller for a University project. At the moment it is going quite well, but I have a niggling bug that is just darn annoying and I can't seem to correct it.
Basically, I have to design a contrasting controller to enable random movement while avoiding obstacles. So, I have a robot which appears as "R" on the console, which is within a 10 by 10 area. Here is the code I use to initialise my 2D vector, and then draw the grid:
void matrix::init() // init my 2D vector
{
dot = 10; // 10 by 10 area
vector2D.resize(dot);
for (int i=0; i<dot; i++)
{
vector2D[i].resize(dot);
}
}
void matrix::draw() // drawing the vector to the screen
{
for(int i=0; i<dot; i++)
{
for(int j=0; j<dot; j++)
{
cout <<vector2D[i][j]<<"."; // I being the Y access, J the X access
}
cout<<endl;
}
}
void matrix::update()
{
init();
draw();
}
This is in its own class called matrix.cpp, which is then called in the main.cpp with m.update(); m being an object of matrix
Now, the robot position on screen is being set with this code within the matrix.cpp class
void matrix::robotPosition(int x, int y)
{
bot = 'R';
cout << "X Pos"<< x <<endl;
cout << "Y Pos"<< y <<endl;
vector2D[x][y] = bot; // Outputting location of robot onto the grid / matrix
}
There is more code I have developed to control the position on screen, but I don't think that is needed at this point in my question.
int main()
{
matrix m;
robot r;
while(true)
{
m.update(); // vector2D init and draw
m.robotPosition(r.getX(), r.getY());
r.update();
system("pause");
}
}
Every time my program loops through the while loop it draws another robot on the screen, but doesn't seem to remove the old one. The code works by assigning a certain X and Y in the 2D vector with the char 'R' (Which is my Robot). Is my thinking correct that I will have to draw the 2D matrix after each movement cycle?
Thanks
When you first set the robot position to, say, (5,5), you will set vector2D[5][5] to R. Then if you set the position to something like (5,6), you will set vector2D[5][6] to R. Now both elements [5][5] and [5][6] are set to R, so the robot is in both positions.
There are a few solutions that depend on how you want to design it:
You can store the current robot position in matrix and at the beginning of robotPosition set that position to whatever the non-robot character is. This will clear the previous position before setting the new one.
You can clear the entire matrix at the beginning of each frame. You are calling update at the beginning of each frame, which attempts to resize the vectors to exactly the same size they already are - this doesn't clear it. Instead, you should do that work in the constructor, and you can turn init into a clear function.
If you want to use a different matrix for each time step, then you need to move the declaration of matrix m; into the while loop. Then you have one for each frame which should be cleared during construction (if you move the init stuff to the constructor).

Interpolation using boost:timer and slerp, quaternions

Im aware this code just looks like a massive block of mess so iv'e done my best to comment what i can... If anyone regularly does skeletal animation im hoping youl see whats going on here.
The problem im having is that float interp = (next-current)/(next-start); is not returning whats expected, e.g. values greater than 1 and minus values... Im guessing this is the whole reason the animations arent being shown and theres no other underlying mistakes.. If there is anything obvious sticking out please let me know.
m_animations stores all the keyframe information for a joint.
void Animation::getRotation(Joint& J) {
int i=0,j=0; //i for bone to animation j for which keyframe in animation
float start, next, current = m_time.elapsed(); //storing time elapsed to keep it the same thoughout method to avoid errors
for (i=0; i<m_animations.size(); i++) {
if(m_animations[i].m_bname == J.name) //finds which bone is being animated
break;
} //retrieve the correct 'anim' for Joint
if (current > m_animations[i].rx_time[m_animations[i].rx_time.size()-1]) { //checks to see if end of animation
m_time.restart();
current = m_time.elapsed(); //resets the animation at its end
}
for (j=0; j<m_animations[i].rx_time.size()-1; j++) {
if(m_animations[i].rx_time[j] >= next && next < m_animations[i].rx_time[j+1]) { //finds the keyframe
start = m_animations[i].rx_time[j]; //start time of current frame
next = m_animations[i].rx_time[j+1]; //end time of current frame
break;
}
}
cout << start <<" "<< current <<" "<< m_time.elapsed() <<" "<< next << endl;
//Get start and end quaternions for slerp
Rotation3 Rj(m_animations[i].rx_angle[j], m_animations[i].ry_angle[j], m_animations[i].rz_angle[j], J.translation);
J.quat = Rj.GetQuat(); //rotating to
Rotation3 R = Rotation3(m_animations[i].rx_angle[j+1], m_animations[i].ry_angle[j+1], m_animations[i].rz_angle[j+1], J.translation);
Quat4 q = R.GetQuat(); //rotating from
float interp = (next-current)/(next-start); //find interpolation point
Quat4 slerp = Slerp(J.quat, q, interp); //sphereical linear interpolation
R = Rotation3(slerp,J.translation);
J.rotation.PasteRotation(R.GetRotationMatrix());
}
Also if it helps heres the update skeleton function that calls getRotation
void Animation::update_skeleton(Joint& J) {
getRotation(J);
J.world.PasteTranslation(J.translation); //world becomes translation matrix
J.world *= J.rotation;
if(J.pName != "") {
J.world = Mat4(J.parent->world) *= J.world; //as not to overwrite the parents world matrix
}
J.translation = J.world.ExtractTranslation();
for(int i=0; i<J.children.size(); i++) {
update_skeleton(*J.children[i]);
}
}
Also when i run my program, it seems to be as if there is only one joint... So im guessing something might be going wrong with the J.translation value during getRotation, but im hoping that fixing my interpolation problem might solve this...
Any help will be VERY appreciated.
You seem to be resetting current before using the original values of start and next, if I've read the code properly that will be causing current to be greater than next, leading to yor negative interpolations.
Turns out there were quite a few mistakes... But the main error was to do with pointers, I fixed it by giving the bones ids for parents, children and itself. Then I changed the functions to take bone id instead of reference to a joint. Problem = fixed :D

Flood fill algorithm in c++

I'm trying to write code that will do a flood fill of a color on an image, and I'm using Stacks. (Still new to stacks and queues, so I'm not sure which one would be a better idea). Anyway, I think I got the basic idea down, but there's a flaw with my code:
animation DFSfill(BMP& img, int x, int y, colorPicker & fillColor, int tolerance, int frameFreq) {
Stack<RGBApixel> s;
s.push(*img(x,y));
int actualTol;
int height, width;
width=img.TellWidth();
height=img.TellHeight();
int counter=1;
animation finalAnimation;
RGBApixel top;
bool visited[width][height];
for(int i=0;i<width;i++)
for(int j=0;j<height;j++)
visited[x][y]=false;
while(!s.isEmpty()){
top = s.peek();
s.pop();
actualTol=(top.Red-fillColor(x,y).Red)^2
+(top.Blue-fillColor(x,y).Blue)^2+(top.Green-fillColor(x,y).Green)^2;
//check
if(x<0 || x>=width)
continue;
if(y<0 || y>=height)
continue;
if (visited[x][y]==true)
continue;
if(actualTol>tolerance)
continue;
visited[x][y]=true;
img(x,y)->Red=fillColor(x,y).Red;
img(x,y)->Blue=fillColor(x,y).Blue;
img(x,y)->Green=fillColor(x,y).Green;
counter++;
//visit adjacent nodes
s.push(*img(x+1, y));//right
s.push(*img(x, y-1));//down
s.push(*img(x-1, y));//left
s.push(*img(x, y+1));//up
if((counter%frameFreq)==0)
finalAnimation.addFrame(img);
}
return finalAnimation;
}
So I think the problem, or to me it seems at least, is that when visiting adjacent nodes, I am visiting the same nodes every loop, right? Whats a workaround to this?
In the stack you are supposed to save the coordinates, not the color. Instead of saving *img(x+1,y) you need to save just x+1,y. you can do this possibly with a struct that holds both coordinates.
Saving the coordinates allows you to travel across the region you're filling. Saving the color doesn't really make any sense.
You could have found this bug on your own by stepping into the code with a debugger step by step and seem what it is that you are pushing into the stack and what it is that gets out of the stack.
A solid understanding of the algorithm before trying to implement it also helps. To get this understanding you can run the algorithm manually with a pen and paper on a small toy example.

Polygon to Polygon Collision Detection Issue

I have been having a few issues implementing my narrow phase collision detection. Broadphase is working perfectly.
I have a group of polygons, that have a stl::vector array of points for their vertices in clockwise order. Every cycle, I check to see whether they're colliding.
I have borrowed the following Point in Polygon test from here and changed it using my Point data structures:
int InsidePolygon(std::vector <Point> poly, Point p) {
int i, j, c = 0;
int nvert = poly.size();
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((poly[i].y> p.y) != (poly[j].y> p.y)) && (p.x < (poly[j].x-poly[i].x) * (p.y-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) )
c = !c;
}
return c;
}
I have extended that to include a PolygonPolygon function, which check all the points of 1 polygon against another and then reverse it to check the other way around.
int PolygonPolygon(std::vector <Point> polygon1, std::vector <Point> polygon2) {
for(int i=0; i<polygon1.size();i++) {
if(InsidePolygon(polygon2, polygon1[i])) {
return 1;
}
}
for(int j=0; j<polygon2.size();j++) {
if(InsidePolygon(polygon1, polygon2[j])) {
return 1;
}
}
return 0;
}
The strange thing is that my PolygonPolygon function is always returning 1. So I have a few questions:
Have I screwed up the logic somewhere? Should I write my PolygonPolygon function differently?
Are there any better methods for a PolygonPolygon test, the polygons themselves are not guaranteed to be convex, which is why I went for the point in polygon method. I also hope to determine which point is colliding eventually, if I can get past this bit.
Should I be presenting my points in a particular order for the InsidePolygon test?
You may want to consider trying to draw a line between polygons as an alternative collision detection method.
[edit] Oops, I missed the fact that you have non-convex polys in there too. Maybe "Determining if a point lies on the interior of a polygon" would be better? Either that or you could break your non-convex polygons up into convex polygons first.
Also, there's at least one similar question here on StackOverflow.
Thanks for your help guys! But i've managed to sort it out on my own.
The importance of translating your vertices to world space and rotating them should not be overlooked, especially if you're colliding them.