lundi 6 novembre 2017

Logical Statement more efficient, 3 lines of code.

and thanks for looking into my case.

Below I attach code, with logical statements. By looking at this code I can see its very repetitive.

My task: 9x9 grid is given to me with 9 boxes inside, i am trying to get the indexes to start loop from (startRow/Col) to (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;
}

I am looking for someone to explain me the better way. Or should I just try to refactor the code and use switch?

Thank you.

Jak

Aucun commentaire:

Enregistrer un commentaire