Intelligent method for particular traversing of a matrix


Intelligent method for particular traversing of a matrix



I have to traverse an n x n matrix in java (so indices are 0,...,n-1), to assign values to the single elements. I must start from the bottom right and arrive to the top left. The particularity is that I do not have to consider the matrix[n-1][n-1] element, that has been initialised before. The adjacent values depend on each other for initialazing and it must be initialized first.


n x n


matrix[n-1][n-1]



One way could be inserting an if in the for cycle


if


for


for (i = n-1; i >= 0; i--)
for (j = n-1; j >= 0; j--)
if (i == n - 1 && j == n - 1)
//initialize particular value
else
//initialize others



but it seems to me a bit inefficient.



Another way could be to initialize the value matrix[n-1][n-1] outside the cycle, then doing 3 for cycles (one for the bottom line, one for the rightest column, one for the other elements). But it seems a bit inelegant.


matrix[n-1][n-1]


for



So I'm searching, if exists, for a solution that involves only two annidate for, and without a control in every cycle (like first example).


for





store the value befor the nested for, and reatribute after the for loops?
– Kepotx
Jun 29 at 10:31





No. The init of adjacent elements depends on it
– Lore
Jun 29 at 10:33




2 Answers
2



Here is an approach that uses one loop through the matrix which makes it easy to avoid matrix[n-1][n-1]. Not sure how the calculations compares to an if though from a performance perspective


int matrix = new int[n][n];

int current = n * n - 2;
int row = 0;
int col = 0;
while (current >= 0) {
col = current % n;
row = current / n;

matrix[row][col] = //init stuff
current--;
}



I think the solution of Joakim is good except the % and / operations... inspired to this, I've found an interesting variant that avoid them. I've called column index j1 to avoid problems with other "normal" cycles.


j1


matrix[n-1][n-1] = //init code;
int j1 = n-2;

for (int i = n-1; i >= 0; i--) {
for (; j1 >= 0; j1--) {
matrix[i][j1] = //init code;
}
j1 = n-1;
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV