Austin Moore
Austin Moore

Reputation: 1412

Is there a more graceful way to find the correct number?

I have a 2D array that acts as a board for a chess game. I expect user input to be in the Smith Notation. The way my array is set up is if the user says they want a piece to move to or from the 8th row (the top one from the user's point of view), they are interacting with row[0] in the array. So to handle this I wrote a function that converts the user's input into the correct row for the array. However, it seems a little clunky and I was wondering how programmers with more experience would solve this problem.

int convertToCorrectRow(int row)
{
    int newRow;
    switch (row) {
        case 1:
            newRow = 7;
            break;
        case 2:
            newRow = 6;
            break;
        case 3:
            newRow = 5;
            break;
        case 4:
            newRow = 4;
            break;
        case 5:
            newRow = 3;
            break;
        case 6:
            newRow = 2;
            break;
        case 7:
            newRow = 1;
            break;
        case 8:
            newRow = 0;
            break;            
        default:
            assert(false);
            break;
    }
    return newRow;
}

I did think of having flipping the array and displaying it in reverse to the user so that when the user interacts with row 8 they are actually interact with row[7] in the array and that would eliminate the need for this function. However, I would still like to know other ways to solve this problem. Thanks in advance for your response.

Upvotes: 2

Views: 78

Answers (2)

Amber
Amber

Reputation: 527063

Why not just...

int convertToCorrectRow(int row)
{
    assert(row < 9 && row > 0);
    return 8 - row;
}

Upvotes: 5

CB Bailey
CB Bailey

Reputation: 792527

It looks like this simplifies to:

int convertToCorrectRow(int row) {
    assert(row > 0 && row <= 8);
    return 8 - row;
}

If row comes from user input without further validation, I wouldn't use an assert, though.

Upvotes: 6

Related Questions