Cout Vector in Random Coordinates n times - c++

I am trying to cout a vector 12 times in a loop at random coordinates. I have created my vector here:
vector<Item> sV(MAXPILLS, pill);
Currently it only prints one of the vector out. This is my code for the random coordinates of the vector and the attempt at printing 12 of them out. I'd appreaciate it if you could help!
void generatePowerPills(char gr[][SIZEX], Item pill){
for (int i = 0; i < 12; i++)
{
gr[pill.y][pill.x] = pill.symbol;
}
}
void initialiseRandomPillsCoordinates(vector<Item>& sV) {
//pass the vector to the function to give each pill random coordinates
Seed();
for (size_t i(0); i < sV.size(); ++i)
{
sV.at(i).y = Random(SIZEY - 2); //vertical coordinate in range [1..(SIZEY - 2)]
sV.at(i).x = Random(SIZEX - 2); //horizontal coordinate in range [1..(SIZEX - 2)]
}
}

I'd just comment but sadly I can only answer. Anyway, you're iterating here:
for (int i = 0; i < 12; i++)
{
gr[pill.y][pill.x] = pill.symbol;
}
But where are you using "i" inside this loop? It seems it will do the same, 12 times. Unless there's some hidden functionality somewhere inside, if so, shame on me.

Related

How to access a vector inside a vector?

So I have a vector of vectors type double. I basically need to be able to set 360 numbers to cosY, and then put those 360 numbers into cosineY[0], then get another 360 numbers that are calculated with a different a now, and put them into cosineY[1].Technically my vector is going to be cosineYa I then need to be able to take out just cosY for a that I specify...
My code is saying this:
for (int a = 0; a < 8; a++)
{
for int n=0; n <= 360; n++
{
cosY[n] = cos(a*vectorOfY[n]);
}
cosineY.push_back(cosY);
}
which I hope is the correct way of actually setting it.
But then I need to take cosY for a that I specify, and calculate another another 360 vector, which will be stored in another vector again as a vector of vectors.
Right now I've got:
for (int a = 0; a < 8; a++
{
for (int n = 0; n <= 360; n++)
{
cosProductPt[n] = (VectorOfY[n]*cosY[n]);
}
CosProductY.push_back(cosProductPt);
}
The VectorOfY is besically the amplitude of an input wave. What I am doing is trying to create a cosine wave with different frequencies (a). I am then calculation the product of the input and cosine wave at each frequency. I need to be able to access these 360 points for each frequency later on in the program, and right now also I need to calculate the addition of all elements in cosProductPt, for every frequency (stored in cosProductY), and store it in a vector dotProductCos[a].
I've been trying to work it out but I don't know how to access all the elements in a vector of vectors to add them. I've been trying to do this for the whole day without any results. Right now I know so little that I don't even know how I would display or access a vector inside a vector, but I need to use that access point for the addition.
Thank you for your help.
for (int a = 0; a < 8; a++)
{
for int n=0; n < 360; n++) // note traded in <= for <. I think you had an off by one
// error here.
{
cosY[n] = cos(a*vectorOfY[n]);
}
cosineY.push_back(cosY);
}
Is sound so long as cosY has been pre-allocated to contain at least 360 elements. You could
std::vector<std::vector<double>> cosineY;
std::vector<double> cosY(360); // strongly consider replacing the 360 with a well-named
// constant
for (int a = 0; a < 8; a++) // same with that 8
{
for int n=0; n < 360; n++)
{
cosY[n] = cos(a*vectorOfY[n]);
}
cosineY.push_back(cosY);
}
for example, but this hangs on to cosY longer than you need to and could cause problems later, so I'd probably scope cosY by throwing the above code into a function.
std::vector<std::vector<double>> buildStageOne(std::vector<double> &vectorOfY)
{
std::vector<std::vector<double>> cosineY;
std::vector<double> cosY(NumDegrees);
for (int a = 0; a < NumVectors; a++)
{
for int n=0; n < NumDegrees; n++)
{
cosY[n] = cos(a*vectorOfY[n]); // take radians into account if needed.
}
cosineY.push_back(cosY);
}
return cosineY;
}
This looks horrible, returning the vector by value, but the vast majority of compilers will take advantage of Copy Elision or some other sneaky optimization to eliminate the copying.
Then I'd do almost the exact same thing for the second step.
std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
std::vector<std::vector<double>> &cosineY)
{
std::vector<std::vector<double>> CosProductY;
for (int a = 0; a < numVectors; a++)
{
for (int n = 0; n < NumDegrees; n++)
{
cosProductPt[n] = (VectorOfY[n]*cosineY[a][n]);
}
CosProductY.push_back(cosProductPt);
}
return CosProductY;
}
But we can make a couple optimizations
std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
std::vector<std::vector<double>> &cosineY)
{
std::vector<std::vector<double>> CosProductY;
for (int a = 0; a < numVectors; a++)
{
// why risk constantly looking up cosineY[a]? grab it once and cache it
std::vector<double> & cosY = cosineY[a]; // note the reference
for (int n = 0; n < numDegrees; n++)
{
cosProductPt[n] = (VectorOfY[n]*cosY[n]);
}
CosProductY.push_back(cosProductPt);
}
return CosProductY;
}
And the next is kind of an extension of the first:
std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
std::vector<std::vector<double>> &cosineY)
{
std::vector<std::vector<double>> CosProductY;
std::vector<double> cosProductPt(360);
for (std::vector<double> & cosY: cosineY) // range based for. Gets rid of
{
for (int n = 0; n < NumDegrees; n++)
{
cosProductPt[n] = (VectorOfY[n]*cosY[n]);
}
CosProductY.push_back(cosProductPt);
}
return CosProductY;
}
We could do the same range-based for trick for the for (int n = 0; n < NumDegrees; n++), but since we are iterating multiple arrays here it's not all that helpful.

creating matrix using 2-d vector c++

im trying to explain the problem i have.
I need a 2-d matrix which contains 233x233 row and columns.
for(int i = 0; i < dimension;i++)
for(int j = 0 ; j < dimension;j++)
distance3 = sqrt(pow((apointCollection2[j].x - apointCollection[i].x1), 2) + pow((apointCollection2[j].y - apointCollection[i].y1), 2));
if (distance3 < Min)
{
Min = distance3;
station = busStation;
}
distance2 = sqrt(pow((apointCollection2[j].x - apointCollection[i].x2), 2) + pow((apointCollection2[j].y - apointCollection[i].y2), 2));
if (distance2 < Min2)
{
Min2 = distance2;
station1 = busStation;
}
So i find the minimum distance and two stations with minimum distance. The first station(station) corresponds to row and the second one (station1) corresponds to column. Then i need to increment the number of people these(can be called route) has.
Then i need to find the station and station1 after the second iteration and if they are the same i need just to increment people and not add the same stations to the vector.
Or another variant i thought
I creat a 2-d vector with 233x233 and 0 values in each cell.
vector< vector<int> > m;
cout << "Filling matrix with test numbers.";
m.resize(233);
for (int i = 0; i < 233; i++)
{
m[i].resize(233);
for (int j = 0; j < 233; j++)
{
}
}
After the loop above i decided to create the following where i find the min distance :
Here i want to increment somehow:
m[station][station1] = person;
if (find(m.begin(), m.end(), station, station1))
{
person++;
}
else
{
m[station][station1] = person;
}
I have an error in "find" because there is no instance of function template.Another problem i don't add values to vector but here also a mistake when i want to add.
This should be done very easy just need to find out the logic i should follow.
Thanks in advance

Replacing duplicates in a randomized 2 dimensional array

I am having some trouble with my class project, essentially what I want to do is spawn objects randomly which so far is working perfectly, they are spawned from an 2d array that stores X and Z which have been randomly generated within reasonable distance. The issue I am having is objects being placed inside each other due to lack of duplicate detection. I need to go through the 2d array, see if any X and Y co-ords match and randomize any matches found. Sorry if this doesn't make a lot of sense, i'm not too good at explaining things but perhaps you could take a look at my current detection method and give me some tips?
for (int k = 0; k <= NumofShrooms - 1; k++)
{
for (int i = 0; i <= NumofShrooms - 1;)
{
if (k == i)
{
i++;
}
if (SpawnArray[k][2] == SpawnArray[i][2])
{
SpawnArray[k][2] = rand() % 16 + 1;
i = 0;
}
else i++;
}
}

Algorithm for smoothing

I wrote this code for smoothing of a curve .
It takes 5 points next to a point and adds them and averages it .
/* Smoothing */
void smoothing(vector<Point2D> &a)
{
//How many neighbours to smooth
int NO_OF_NEIGHBOURS=10;
vector<Point2D> tmp=a;
for(int i=0;i<a.size();i++)
{
if(i+NO_OF_NEIGHBOURS+1<a.size())
{
for(int j=1;j<NO_OF_NEIGHBOURS;j++)
{
a.at(i).x+=a.at(i+j).x;
a.at(i).y+=a.at(i+j).y;
}
a.at(i).x/=NO_OF_NEIGHBOURS;
a.at(i).y/=NO_OF_NEIGHBOURS;
}
else
{
for(int j=1;j<NO_OF_NEIGHBOURS;j++)
{
a.at(i).x+=tmp.at(i-j).x;
a.at(i).y+=tmp.at(i-j).y;
}
a.at(i).x/=NO_OF_NEIGHBOURS;
a.at(i).y/=NO_OF_NEIGHBOURS;
}
}
}
But i get very high values for each point, instead of the similar values to the previous point . The shape is maximized a lot , what is going wrong in this algorithm ?
What it looks like you have here is a bass-ackwards implementation of a finite impulse response (FIR) filter that implements a boxcar window function. Thinking about the problem in terms of DSP, you need to filter your incoming vector with NO_OF_NEIGHBOURS equal FIR coefficients that each have a value of 1/NO_OF_NEIGHBOURS. It is normally best to use an established algorithm rather than reinvent the wheel.
Here is a pretty scruffy implementation that I hammered out quickly that filters doubles. You can easily modify this to filter your data type. The demo shows filtering of a few cycles of a rising saw function (0,.25,.5,1) just for demonstration purposes. It compiles, so you can play with it.
#include <iostream>
#include <vector>
using namespace std;
class boxFIR
{
int numCoeffs; //MUST be > 0
vector<double> b; //Filter coefficients
vector<double> m; //Filter memories
public:
boxFIR(int _numCoeffs) :
numCoeffs(_numCoeffs)
{
if (numCoeffs<1)
numCoeffs = 1; //Must be > 0 or bad stuff happens
double val = 1./numCoeffs;
for (int ii=0; ii<numCoeffs; ++ii) {
b.push_back(val);
m.push_back(0.);
}
}
void filter(vector<double> &a)
{
double output;
for (int nn=0; nn<a.size(); ++nn)
{
//Apply smoothing filter to signal
output = 0;
m[0] = a[nn];
for (int ii=0; ii<numCoeffs; ++ii) {
output+=b[ii]*m[ii];
}
//Reshuffle memories
for (int ii = numCoeffs-1; ii!=0; --ii) {
m[ii] = m[ii-1];
}
a[nn] = output;
}
}
};
int main(int argc, const char * argv[])
{
boxFIR box(1); //If this is 1, then no filtering happens, use bigger ints for more smoothing
//Make a rising saw function for demo
vector<double> a;
a.push_back(0.); a.push_back(0.25); a.push_back(0.5); a.push_back(0.75); a.push_back(1.);
a.push_back(0.); a.push_back(0.25); a.push_back(0.5); a.push_back(0.75); a.push_back(1.);
a.push_back(0.); a.push_back(0.25); a.push_back(0.5); a.push_back(0.75); a.push_back(1.);
a.push_back(0.); a.push_back(0.25); a.push_back(0.5); a.push_back(0.75); a.push_back(1.);
box.filter(a);
for (int nn=0; nn<a.size(); ++nn)
{
cout << a[nn] << endl;
}
}
Up the number of filter coefficients using this line to see a progressively more smoothed output. With just 1 filter coefficient, there is no smoothing.
boxFIR box(1);
The code is flexible enough that you can even change the window shape if you like. Do this by modifying the coefficients defined in the constructor.
Note: This will give a slightly different output to your implementation as this is a causal filter (only depends on current sample and previous samples). Your implementation is not causal as it looks ahead in time at future samples to make the average, and that is why you need the conditional statements for the situation where you are near the end of your vector. If you want output like what you are attempting to do with your filter using this algorithm, run the your vector through this algorithm in reverse (This works fine so long as the window function is symmetrical). That way you can get similar output without the nasty conditional part of algorithm.
in following block:
for(int j=0;j<NO_OF_NEIGHBOURS;j++)
{
a.at(i).x=a.at(i).x+a.at(i+j).x;
a.at(i).y=a.at(i).y+a.at(i+j).y;
}
for each neighbour you add a.at(i)'s x and y respectively to neighbour values.
i understand correctly, it should be something like this.
for(int j=0;j<NO_OF_NEIGHBOURS;j++)
{
a.at(i).x += a.at(i+j+1).x
a.at(i).y += a.at(i+j+1).y
}
Filtering is good for 'memory' smoothing. This is the reverse pass for the learnvst's answer, to prevent phase distortion:
for (int i = a.size(); i > 0; --i)
{
// Apply smoothing filter to signal
output = 0;
m[m.size() - 1] = a[i - 1];
for (int j = numCoeffs; j > 0; --j)
output += b[j - 1] * m[j - 1];
// Reshuffle memories
for (int j = 0; j != numCoeffs; ++j)
m[j] = m[j + 1];
a[i - 1] = output;
}
More about zero-phase distortion FIR filter in MATLAB: http://www.mathworks.com/help/signal/ref/filtfilt.html
The current-value of the point is used twice: once because you use += and once if y==0. So you are building the sum of eg 6 points but only dividing by 5. This problem is in both the IF and ELSE case. Also: you should check that the vector is long enough otherwise your ELSE-case will read at negative indices.
Following is not a problem in itself but just a thought: Have you considered to use an algorithm that only touches every point twice?: You can store a temporary x-y-value (initialized to be identical to the first point), then as you visit each point you just add the new point in and subtract the very-oldest point if it is further than your NEIGHBOURS back. You keep this "running sum" updated for every point and store this value divided by the NEIGHBOURS-number into the new point.
You make addition with point itself when you need to take neighbor points - just offset index by 1:
for(int j=0;j<NO_OF_NEIGHBOURS;j++)
{
a.at(i).x += a.at(i+j+1).x
a.at(i).y += a.at(i+j+1).y
}
This works fine for me:
for (i = 0; i < lenInput; i++)
{
float x = 0;
for (int j = -neighbours; j <= neighbours; j++)
{
x += input[(i + j <= 0) || (i + j >= lenInput) ? i : i + j];
}
output[i] = x / (neighbours * 2 + 1);
}

I cannot get code to separate and compare array data correctly

I've got an fstream input file that has [N] lines or items. I've written code to decide which items are triangles and which are rectangles and which are circles. I've got to isolate just the triangle items and then compare them to see if they are equal to +/- 0.1 the area of all the other triangle items. Then I have to cout the equal pairs of items as uppercase char letters.
Here's my code so far but it's not working correctly. It's outputting L&L, which is incorrect. It should say E&L because the two identical triangles in my array are on lines 5&12, Not 12&12. How do I fix this?
int ItmM = 0;
ItmN = 0;
int j = 0;
for (int i=0; i<M; i++)
{
if (btype[i] == Triangles)
{
TA[i] = (0.5 * (D[i] * E[i]));
for (int j=0; j<i; j++)
{
if (TA[i] - 0.1 < TA[j] && TA[j] < TA[i] + 0.1)
{
TA[j] = TA[i];
ItmM = i;
ItmN = j;
cout << "4. Triangular blocks that are the same size = "
<< (char)('A' + ItmM) << "&" << (char)('A' + ItmM)
<< endl;
}
}
}
}
I've edited the above code twice. It's still outputting L&L. Should be E&L, (5&12)
When you do TriangleAreaE = TrangleArea[j], and as j is always0, you are comparing every triangle with the first one. The 5th and 12th never get compared.
You should use a nested loop to compare every pair of triangles:
for (int i=0; i<M; i++)
{
if ( /*...*/ )
{
/*...*/
for (int j=0; j<i; j++)
{
// compare TriangleArea[i] with TriangleArea[j], if j is a triangle
}
}
}
You can fill in the detail, as this seems to be a homework problem.
And you should edit your existing posts instead of posting a new one.
The value of j never changes in the code you posted. You just compare the area of each triangle with the first one in the list. If I understand what you are trying to do correctly, you should be able to make it work with a nested for loop:
TriangleArea[0]= whatever
for(j=0; j<M; j++)
{
for(i=j+1;i<m;i++)
{
// rest of your code
In your code you never modify j, so you are always comparing with the first triangle (triangle A), so it's not really a suprise that it is equal to itself. What you need to do is loop over all already processed triangles and compare, so basically
for (int i=0; i<M; i++)
{
if (btype[i] == Triangles) //btype[i] declared earlier in larger code
{
TriangleArea[i] = (0.5 * (D[i] * E[i]));
for(int j = 0; j < i; ++j)
{
//Insert the comparison here
}
}
}
Of course your positioning of the cout will only print the last pair of equal sized pair, so judging from the text in your question, you might want to put the cout inside your loops.
(char)('A' + ItemNumberM) << "&" << (char)('A' + ItemNumberM)
This line prints the same item number twice. Is one of those supposed to be ItemNumberN?