简体   繁体   中英

Using std:sort to sort locally

I am making a Soduku solver, so I need to test for legality in the rows, columns and squares. I have functions to do each.

bool Board::isRowLegal(int row){
    sort(theBoard[row].begin(), theBoard[row].end());
    for(int i = 1; i < theBoard[row].size() - 1; ++i){
        if(theBoard[row][i] != 0){
            if(theBoard[row][i] == theBoard[row][i + 1]){
                return false;           
            }   
        }
    }
    return true;
}

bool Board::isColumnLegal(int column){
    vector<int> currentColumn;
    int current = 0;
    for(int i = 1; i < theBoard.size(); ++i){
        currentColumn.push_back(theBoard[i][column]);
    }

    sort(currentColumn.begin(), currentColumn.end());
    for(int j = 0; j < currentColumn.size() - 1; ++j){
        if(currentColumn[j] != 0){
            if(currentColumn[j] == currentColumn[j + 1]){
                return false;           
            }   
        }
    }
    return true;
}

bool Board::isPanelLegal(int rowStart, int colStart){
    vector<int> currentPanel;
    for(int i = rowStart; i < rowStart + THREE; ++i){
        for(int j = colStart; j < colStart + THREE; ++j){
            currentPanel.push_back(theBoard[i][j]);
        }
    }
    sort(currentPanel.begin(), currentPanel.end());
    for(int k = 0; k < currentPanel.size() - 1; ++k){
        if(currentPanel[k] != ZERO){
            if(currentPanel[k] == currentPanel[k + 1]){
                return false;           
            }   
        }
    }   
    return true;
}

I sort the board so that I can test for duplicates. I run into the problem when my program hits the isColumnLegal function. It appears that the vector of the board has already been sorted corresponding to its rows, that means my column function cannot detect column legality because the rows do not correspond anymore. So my question is, is there a way to use the std::sort function, and sort locally, WITHOUT copying the vector into another vector ? As you can imagine, this program is already inefficient and I hate to make it any more by copying vectors. I know it is only a 10 by 10 vector of int but still.

Create an array of 9 bool elements, initialized to false. Loop through the vector, setting to true the indexes (minus one) of any number you find. If, in this process, you run into an element that is already set to true, the row is invalid.

bool present[9] = {};
for (auto const i : theBoard[row])
{
    if (i != 0)
    {
        if (present[i-1])
            return false;
        present[i-1] = true;
    }
}
return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM