Reputation: 1632
I am trying to figure out how to reverse a for loop, it is kinda hard to explain so I will provide an example:
var data_base_array = [3, 3, 1, 4, 1];
var points = [];
for (var index = 0; index <= 4; index++){
points.push(point_xy_cords[data_base_array[index]][index]);
}
data_base_array
contains numbers between 1-5. Another array contains coordinates of points called point_xy_cords
. I want to know if there are any methods I can use to reverse this forloop. I can't wrap my head around it, so some logical technique would help get me in the right direction.
If the array points
change for example, I want to change data_base_array
accordingly. The values of point_xy_cords looks something like this:
point_xy_cords[1-5][0-4][0-1]
so if point_xy_cords[1][0]
then it would give result of two values, (123.12, 242.11)
.
If point_xy_cords[1][0][0]
then it would give result of 123.12
.
I'm looking for a solution something like this:
for (var x = 1; x <= 5; x++){
for (var y = 0; y <= 4; y++){
if (points[y][0] == point_xy_cords[x][y][0] && points[y][1] == point_xy_cords[x][y][1]){
data_base_array[y] = x;
}
}
}
The above possible solution didn't work. Any direction would be appreciated. Danke.
Upvotes: 0
Views: 80
Reputation: 3622
I think you almost got it...
So the relation between your 2 arrays is :
i1 i2, ...
data_base_array [ j1, j2, ... ]
i1 , i2 , ...
points [ point_xy_cords[j1][i1], point_xy_cords[j2][i2], ... ]
So iX
is the index and jX
is the value on the data_base_array
array (where X
is a number). Also iX
is the index and point_xy_cords[jX][iX]
is the value on the points
array. So the index of the arrays data_base_array
and points
is the same (iX
).
In order to reconstruct he data_base_array
array, if we know the points
and the point_xy_cords
arrays, we need to know the jX
, but we don't. So we need to search all the possible jX
to find a possible match on the points[iX] == point_xy_cords[jX][iX]
.
The reconstruction can be done with the code :
// Init array
var data_base_array = [];
// For each `iX` (from 0 to 4)
for (var i = 0; i <= 4; i++){
// Init to an invalid number
data_base_array[i] = 0; // Zero is invalid
// Find correct `jX` (so search from 1 to 5)
for (var j = 1; j <= 5; j++){
// Check if `points[iX] == point_xy_cords[jX][iX]`
if (
// Javascript can't compare arrays, so compare each array item
points[i][0] == point_xy_cords[j][i][0] &&
points[i][1] == point_xy_cords[j][i][1]
){
// We found a possible `jX`
data_base_array[i] = j;
// Stop search
break;
}
}
}
But this is 100% correct, only if you are sure that the pairs in the point_xy_cords[i][j]
are unique on each column.
Upvotes: 1