C++ Nested for loops - c++

I am writing a program that modifies data in a csv file.
In the csv file, the COLUMNS are organized as follows..
X-coordinate, Y-coordinate, Z-coordinate, info, X, Y, Z, info, X, Y, Z info..
The first X-coordinate begins in column 4 and the next one is 4 columns after, in 8. For Y, it's column 5 and column 9, so on. Since I saved the data onto a deque, the first ones correspond to data[row#][3] for x, and y would be data[row#][5].
for(int k=0; k<618; k++) { //all rows 618
for(int l=3; l<96; l=l+4) { //x columns
for(int m=4; m<97; m=m+4) { //y columns
data[k][l] = (data[k][l] )*(data[k][2]) + (data[k][m])*(data[k][1]);
In the calculation in the loop, I want it to replace all the x values (l) in columns (k) with the value I get from this equation (as I created for the loop)
x' = x* cos(theta) + y* sin(theta)
the values for cos(theta) and sin(theta) are found in columns 2 and 3 for all the rows (hence, data[k][2] and data[k][1].
Unfortunately, in testing this out with several cout statements, I noticed it is not doing as desired.
DESIRED BEHAVIOR OF LOOP:
1st time through loop: Calculation is done for row 1, x = value inside column 4 and y= value in col.5
*end of loop iteration, re-start, k, l, and m get updated to 2,9,10.
Calculation in the loop is executed for these new values, so on.
Main issue is k, l, m are not all three being updated as desired after the data[k][l] line What could be causing this?
Thank you.

You do not understand nested loops.
What you intend is something like this:
for(int k=0; k<618; k++) { //all rows 618
for(int n=0; n<24; ++n) { //groups
l = 4*n + 3;
m = 4*n + 4
data[k][l] = (data[k][l] )*(data[k][2]) + (data[k][m])*(data[k][1]);
}
}

Related

selecting vector based on index in R vs rcpp

EDIT
After doing some more reading around C++, I managed to concise my question on what exactly I want to do. Basically, I have two vectors:
my_vec <- c(270, 291, 330, 378)
x <- 1:109
The four elements of my_vec correspond to 1st, 23rd, 61st and 109th element of vector x I want to write an Rcpp code that sums up x from 1:23rd value, 24th to 61st value and 62nd to 109th value as shown below in R:
sum(x[1:22]) # 253
sum(x[23:61]) # 1638
sum(x[62:109]) # 4104
I wrote the following Rcpp code to this:
library(Rcpp)
cppFunction('
List sum_calc(NumericVector x,
NumericVector my_vec){
int n = my_vec.size();
NumericVector sum_vec (n-1);
double sum;
int start_counter;
int counter = 0;
int start;
int end;
for(int i=0; i<(n-1); ++i){
start = my_vec[i];
end = my_vec[i + 1];
double x_sum = 0;
start_counter = start;
while(start_counter <= end){
x_sum += x[counter];
counter += 1;
start_counter += 1;
};
sum_vec[i] = x_sum;
};
return Rcpp::List::create(Rcpp::Named("sum_vec") = sum_vec);
}
')
sum_calc(x, my_vec)
$sum_vec
[1] 253 1700 4042
However only the first result is matching my output while the others two don't. I think this is an index question but I don't know how to go about it. I have read C++ online and some material but still I cannot solve this. Where I am getting it wrong?

Find out If a list of (x,y) coordinates span a row or column in a matrix

So, I have a list of x,y coordiates. I want to find out whether that list of coordinates span all rows of a matrix of values and same for columns.
i.e.
T F F F
T T F F
F T F F
F T T F
Here the group of T's are provided as coordinates so it would be something like [(0,0),(0,1),(1,1),(1,2),(1,3),(2,3)]. How can i find out using these coordinates that the set they describe spans all rows of the matrix? This also applies to columns, as well as both ( so, whether the set spans both rows and columns ).
The values are currently stored as vector<vector<coord>> where coord is a struct like :
struct coord {
int x, int y;
}
Assuming that all you have is the size of the matrix (m x n = row x column) and the position of T's in term of coordinates (std::vector<std::vector<coord>>), you can do:
std::vector<std::vector<coord>> Ts_pos;
std::set<int> rows;
std::set<int> cols;
bool spansRow = false;
bool spansCol = false;
for (int i = 0; i < Ts_pos.size(); i++)
{
for (int j = 0; j < Ts_pos[i].size(); j++)
{
item = Ts_pos[i][j];
cols.insert(item.x);
rows.insert(item.y);
}
}
if (rows.size() == numRows) spansRow = true;
if (cols.size() == numCols) spansCol = true;
After executing the loop, the two set will contain the index number of the rows and of the columns touched by the T's, i.e: consider, in you exemple, the first T. It has coordinates (0,0) so it touches the column with index 0 and the row with the index 0, so you insert 0 in the row set and 0 in the col set. Then, you consider the second T in your list and so on.
Outside the loop, you can discover if all rows have been touched simply querying for the size of the row set. If it is equal to the number of rows of the matrix, then, all the rows have been touched and the set of T's spans the matrix by row, at least.
The same you do for the column set.
Then you can std::cout what you want according to the value of spansRow and spansCol.
We can store all the x-coordinates and all the y-coordinates in separate vectors, sort these vectors and check if values from 0-n are present in each vector (where n is the no. of rows for x-vector and no. of columns for y-vector).
Missing values, values ranging to less than n, values starting from greater than 0, etc will provide us with the answer whether the set spans both rows and columns.
You just need to de-duplicate the xs and the ys, and compare them to the required indexes. E.g.
std::set<int> required = { 0, 1, 2, 3 }; // values that must be present
bool spans_direction(const std::vector<coord> & coords, std::function<int(coord)> projection)
{
std::set<int> projected;
std::transform(coords.begin(), coords.end(), std::inserter(projected, projected.end()), projection);
return projected == required;
}
bool spans_cols(const std::vector<coord> & coords)
{
return spans_direction(coords, [](coord c) { return c.x; });
}
bool spans_rows(const std::vector<coord> & coords)
{
return spans_direction(coords, [](coord c) { return c.y; });
}

Euclidean distance between each record with other records in an array

so i have an array [nm] and i need to code in c++ the Euclidean distance between each row and the other rows in the array and store it in a new distance-array [nn] which every cell's value is the distance between the intersected rows.
distance-array:
r0 r1 .....rn
r0 0
r1 0
. 0
. 0
rn 0
the Euclidean distance between tow rows or tow records is:
assume we have these tow records:
r0: 1 8 7
r1: 2 5 3
r2
.
.
rn
Euclidean distance between r0 and r1 = sqrt((1-2)^2+(8-5)^2+(7-3)^2)
to code this i used 4 loops(which i think is too much) but i couldn't do it right, can someone help me to code this without using 3-D array ??
this is my code:
int norarr1[row][column] = { 1,1,1,2,2,2,3,3,3 };
int i = 0; int j = 0; int k = 0; int l = 0;
for (i = 0; i < column; i++){
for(j = 0; j < column; j++){
sumd = 0;
for (k = 0; k < row; k++) {
for (l = 0; l < row; l++) {
dist = sqrt((norarr1[i][k] - norarr1[j][l]) ^ 2);
sumd = sumd + dist;
cout << "sumd =" << sumd << " ";
}
cout << endl;
}
disarr[j][i] = sumd;
disarr[i][j] = sumd;
cout << disarr[i][j];
}
cout << endl;
}
There are several problems with your code. For now, let's ignore the for loops. We'll get to that later.
The first thing is that ^ is the bitwise exclusive or (XOR) operator. It does not do exponentiation like in some other languages. Instead, you need to use std::pow().
Second, you are summing square roots, which is not the correct way to calculate Euclidean distance. Instead, you need to calculate a sum and then take the square root.
Now let's think about the for loops. Assume that you already know which two rows you want to calculate the distance between. Call these r1 and r2. Now you just need to pair one coordinate from r1 with one coordinate from r2. Note that these coordinates will always be in the same column. This means that you only need one loop to calculate the squares of the differences of each pair of coordinates. Then you sum these squares. Finally after this single loop you take the square root.
With that out of the way, we need to iterate over the rows to choose each r1 and r2. Okay, this will take two loops since we want each of these to take on the value of each row.
In total, we will need three for loops. You can make this easier to understand by designing your code well. For example, you can create a class or struct that holds each row. If you know that every row is only three dimensions, then create a point or vector3 class. Now you can write a function which calculates the distance between two points. Finally, store the list of points as a 1D array. In fact, breaking up the data and calculation in this way makes the previous discussion about calculating the distance even easier to understand.

Diagonally Sorting a Two Dimensional Array in C++ [duplicate]

I'm building a heatmap-like rectangular array interface and I want the 'hot' location to be at the top left of the array, and the 'cold' location to be at the bottom right. Therefore, I need an array to be filled diagonally like this:
0 1 2 3
|----|----|----|----|
0 | 0 | 2 | 5 | 8 |
|----|----|----|----|
1 | 1 | 4 | 7 | 10 |
|----|----|----|----|
2 | 3 | 6 | 9 | 11 |
|----|----|----|----|
So actually, I need a function f(x,y) such that
f(0,0) = 0
f(2,1) = 7
f(1,2) = 6
f(3,2) = 11
(or, of course, a similar function f(n) where f(7) = 10, f(9) = 6, etc.).
Finally, yes, I know this question is similar to the ones asked here, here and here, but the solutions described there only traverse and don't fill a matrix.
Interesting problem if you are limited to go through the array row by row.
I divided the rectangle in three regions. The top left triangle, the bottom right triangle and the rhomboid in the middle.
For the top left triangle the values in the first column (x=0) can be calculated using the common arithmetic series 1 + 2 + 3 + .. + n = n*(n+1)/2. Fields in the that triangle with the same x+y value are in the same diagonal and there value is that sum from the first colum + x.
The same approach works for the bottom right triangle. But instead of x and y, w-x and h-y is used, where w is the width and h the height of rectangle. That value have to be subtracted from the highest value w*h-1 in the array.
There are two cases for the rhomboid in the middle. If the width of rectangle is greater than (or equal to) the height, then the bottom left field of the rectangle is the field with the lowest value in the rhomboid and can be calculated that sum from before for h-1. From there on you can imagine that the rhomboid is a rectangle with a x-value of x+y and a y-value of y from the original rectangle. So calculations of the remaining values in that new rectangle are easy.
In the other case when the height is greater than the width, then the field at x=w-1 and y=0 can be calculated using that arithmetic sum and the rhomboid can be imagined as a rectangle with x-value x and y-value y-(w-x-1).
The code can be optimised by precalculating values for example. I think there also is one formula for all that cases. Maybe i think about it later.
inline static int diagonalvalue(int x, int y, int w, int h) {
if (h > x+y+1 && w > x+y+1) {
// top/left triangle
return ((x+y)*(x+y+1)/2) + x;
} else if (y+x >= h && y+x >= w) {
// bottom/right triangle
return w*h - (((w-x-1)+(h-y-1))*((w-x-1)+(h-y-1)+1)/2) - (w-x-1) - 1;
}
// rhomboid in the middle
if (w >= h) {
return (h*(h+1)/2) + ((x+y+1)-h)*h - y - 1;
}
return (w*(w+1)/2) + ((x+y)-w)*w + x;
}
for (y=0; y<h; y++) {
for (x=0; x<w; x++) {
array[x][y] = diagonalvalue(x,y,w,h);
}
}
Of course if there is not such a limitation, something like that should be way faster:
n = w*h;
x = 0;
y = 0;
for (i=0; i<n; i++) {
array[x][y] = i;
if (y <= 0 || x+1 >= w) {
y = x+y+1;
if (y >= h) {
x = (y-h)+1;
y -= x;
} else {
x = 0;
}
} else {
x++;
y--;
}
}
What about this (having an NxN matrix):
count = 1;
for( int k = 0; k < 2*N-1; ++k ) {
int max_i = std::min(k,N-1);
int min_i = std::max(0,k-N+1);
for( int i = max_i, j = min_i; i >= min_i; --i, ++j ) {
M.at(i).at(j) = count++;
}
}
Follow the steps in the 3rd example -- this gives the indexes (in order to print out the slices) -- and just set the value with an incrementing counter:
int x[3][3];
int n = 3;
int pos = 1;
for (int slice = 0; slice < 2 * n - 1; ++slice) {
int z = slice < n ? 0 : slice - n + 1;
for (int j = z; j <= slice - z; ++j)
x[j][slice - j] = pos++;
}
At a M*N matrix, the values, when traversing like in your stated example, seem to increase by n, except for border cases, so
f(0,0)=0
f(1,0)=f(0,0)+2
f(2,0)=f(1,0)+3
...and so on up to f(N,0). Then
f(0,1)=1
f(0,2)=3
and then
f(m,n)=f(m-1,n)+N, where m,n are index variables
and
f(M,N)=f(M-1,N)+2, where M,N are the last indexes of the matrix
This is not conclusive, but it should give you something to work with. Note, that you only need the value of the preceding element in each row and a few starting values to begin.
If you want a simple function, you could use a recursive definition.
H = height
def get_point(x,y)
if x == 0
if y == 0
return 0
else
return get_point(y-1,0)+1
end
else
return get_point(x-1,y) + H
end
end
This takes advantage of the fact that any value is H+the value of the item to its left. If the item is already at the leftmost column, then you find the cell that is to its far upper right diagonal, and move left from there, and add 1.
This is a good chance to use dynamic programming, and "cache" or memoize the functions you've already accomplished.
If you want something "strictly" done by f(n), you could use the relationship:
n = ( n % W , n / H ) [integer division, with no remainder/decimal]
And work your function from there.
Alternatively, if you want a purely array-populating-by-rows method, with no recursion, you could follow these rules:
If you are on the first cell of the row, "remember" the item in the cell (R-1) (where R is your current row) of the first row, and add 1 to it.
Otherwise, simply add H to the cell you last computed (ie, the cell to your left).
Psuedo-Code: (Assuming array is indexed by arr[row,column])
arr[0,0] = 0
for R from 0 to H
if R > 0
arr[R,0] = arr[0,R-1] + 1
end
for C from 1 to W
arr[R,C] = arr[R,C-1]
end
end

How to map the indexes of a matrix to a 1-dimensional array (C++)?

I have an 8x8 matrix, like this:
char matrix[8][8];
Also, I have an array of 64 elements, like this:
char array[64];
Then I have drawn the matrix as a table, and filled the cells with numbers, each number being incremented from left to right, top to bottom.
If I have, say, indexes 3 (column) and 4 (row) into the matrix, I know that it corresponds to the element at position 35 in the array, as it can be seen in the table that I've drawn. I believe there is some sort of formula to translate the 2 indexes of the matrix into a single index of the array, but I can't figure out what it is.
Any ideas?
The way most languages store multi-dimensional arrays is by doing a conversion like the following:
If matrix has size, n (rows) by m (columns), and we're using "row-major ordering" (where we count along the rows first) then:
matrix[ i ][ j ] = array[ i*m + j ].
Here i goes from 0 to (n-1) and j from 0 to (m-1).
So it's just like a number system of base 'm'. Note that the size of the last dimension (here the number of rows) doesn't matter.
For a conceptual understanding, think of a (3x5) matrix with 'i' as the row number, and 'j' as the column number. If you start numbering from i,j = (0,0) --> 0. For 'row-major' ordering (like this), the layout looks like:
|-------- 5 ---------|
Row ______________________ _ _
0 |0 1 2 3 4 | |
1 |5 6 7 8 9 | 3
2 |10 11 12 13 14| _|_
|______________________|
Column 0 1 2 3 4
As you move along the row (i.e. increase the column number), you just start counting up, so the Array indices are 0,1,2.... When you get to the second row, you already have 5 entries, so you start with indices 1*5 + 0,1,2.... On the third row, you have 2*5 entries already, thus the indices are 2*5 + 0,1,2....
For higher dimension, this idea generalizes, i.e. for a 3D matrix L by N by M:
matrix[ i ][ j ][ k ] = array[ i*(N*M) + j*M + k ]
and so on.
For a really good explanation, see: http://www.cplusplus.com/doc/tutorial/arrays/; or for some more technical aspects: http://en.wikipedia.org/wiki/Row-major_order
For row-major ordering, I believe the statement matrix[ i ][ j ] = array[ i*n + j ] is wrong.
The offset should be offset = (row * NUMCOLS) + column.
Your statement results to be row * NUMROWS + column, which is wrong.
The links you provided give a correct explanation.
Something like this?
//columns = amount of columns, x = column, y = row
var calculateIndex = function(columns, x, y){
return y * columns + x;
};
The example below converts an index back to x and y coordinates.
//i = index, x = amount of columns, y = amount of rows
var calculateCoordinates = function(index, columns, rows){
//for each row
for(var i=0; i<rows; i++){
//check if the index parameter is in the row
if(index < (columns * i) + columns && index >= columns * i){
//return x, y
return [index - columns * i, i];
}
}
return null;
};