javafor-loopmatrixmultidimensional-arraydiagonal

Loop diagonally on top half of a square matrix in Java?


Not sure how to structure the loop to iterate the matrix in this order. The red is the middle diagonally which should be ignored. The yellow is the cells I need to process but in the order of the arrows from bottom to top (bigger arrow to smaller arrow). Is it possible? If anyone can provide iteration logic I would highly appreciate it!

enter image description here


Solution

  • the following is the iteration structure that you need

    for(int i = 1; i < matrix.size; ++i)
        for(int j = 0; j < matrix.size - i; ++j)
            matrix[j][i+j] //do your stuff
    

    if you needed a wrap around diagonal instead:

    for(int i = 1; i < matrix.size; ++i)
        for(int j = 0; j < matrix.size; ++j)
            matrix[j][(i+j)%matrix.size] //do your stuff