简体   繁体   中英

c++ console Check adjacent elements for duplicates

I have a grid of randomly generated numbers of size gameSize (user input) which is contained within a vector of vectors. The user can enter two co-ordinates (x, y) so that it changes a number within the grid to a predefined value, which is "0".

So for example the user enters, X:0 Y:0 and:

{9, 7, 9}

{9, 6, 8}

{5, 1, 4}

becomes:

{0, 7, 9} <-- Changes position 0,0 to 0 (the predefined value)

{9, 6, 8} 

{5, 1, 4}

For example, the following would not be allowed because three 0's clash.

    {0, 0, 9}

    {0, 6, 8}

    {5, 1, 4}

But the following WOULD be valid:

{0, 7, 0}

{9, 0, 8}

{5, 1, 4}

Try this:

if (
    (row == 0 || myGame[row-1][col] != 0) // element above (if applicable)
    && (row == gameSize-1 || myGame[row+1][col] != 0) // element below
    && (col == 0 || myGame[row][col-1] != 0) // element to the left
    && (col == gameSize-1 || myGame[row][col+1] != 0) // element to the right
    )
    myGame[row][col] = 0;
else
...

Each condition checks for an adjacent element only if it's there (taking advantage of short-circuit evaluation , see here under Logical operators). In other words, for instance, myGame[row-1][col] is checked only if row == 0 is false, thus preventing crashes due to unauthorized memory accesses.

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