编程语言
首页 > 编程语言> > Java-避免矩阵迭代中的代码重复

Java-避免矩阵迭代中的代码重复

作者:互联网

假设我有一个int [size] [size]矩阵.我想像这样遍历它:

01 02 03 04
08 07 06 05
09 10 11 12
16 15 14 13

我真的必须说:

for (int y=0; y<size; y++) {
    int startIndex, endIndex, increment;
    boolean lessThan;
    if (y%2 == 0) {
        startIndex = 0;
        endIndex = size;
        lessThan = true;
        increment = 1;
    }
    else {
        startIndex = size-1;
        endIndex = -1;
        lessThan = false;
        increment = -1;
    }
    for (int x=startIndex; lessThan ? x<endIndex : x>endIndex; x+=increment) {
        // Process element
    }
}

为了避免这样做:

for (int y=0; y<size; y++) {
    if (y%2 == 0) {
        for (int x=0; x<size; x++) {
            // Process element
        }
    }
    else {
        for (int x=size-1; x>-1; x--) {
            // Process element
        }
    }
}

更好,但是重复了代码.有没有更好的方法来构造它?

解决方法:

遍历矩阵的另一种方法:

for (int num = 0; num < maxX*maxY; ++num) { // num - element number
    // calc element coordinates
    int y = num / maxX;
    int x = num % maxX;
    if (y % 2 == 1)
       x = maxX - x;
    int elem = matrix[x][y];
    // process element
}

标签:code-duplication,java,refactoring
来源: https://codeday.me/bug/20191121/2054361.html