重构使用 if 语句的重复范围检查

Refactoring repeated range checks which use if statements

本文关键字:范围 检查 语句 if 重构      更新时间:2023-10-16

下面我附上代码,带有逻辑语句。通过查看此代码,我可以看到它非常重复。

的任务:9x9 网格给了我,里面有 9 个盒子,我正在尝试让索引开始从 ( startRow/Col) 到 ( startRow/Col+2) 的循环。

vector<int> findBox(int row, int col){
    int startRow;
    int startCol;
    if(row <= 2){
        startRow = 0;
    } else if(row > 2 && row <= 5){
        startRow = 3;
    } else if(row > 5 && row <= 8){
        startRow = 6;
    }
    if(col <= 2){
        startCol = 0;
    } else if (col > 2 && col <= 5){
        startCol = 3;
    } else if(col > 5 && col <= 8){
        startCol = 6;
    }
    vector<int> v;
    v.push_back(startRow);
    v.push_back(startCol);
    return v;
}

正在寻找有人来解释我更好的方法。还是我应该尝试重构代码并使用开关?

谢谢。

杰克

无需使用开关。利用整数除法,这将丢弃余数:

int startRow{row / 3 * 3};
int startCol{col / 3 * 3};

然后,该函数变为:

vector<int> findBox(int row, int col){
    int startRow{row / 3 * 3};
    int startCol{col / 3 * 3};
    vector<int> v;
    v.push_back(startRow);
    v.push_back(startCol);
    return v;
}

也许

vector<int> findBox (int row, int col)
 { return { (row - row % 3), (col - col % 3) }; }